python之文件操作

      使用python进行文件操作

      使用:

          场景一:     逐行读取文件中的内容

filename = 'sentiment_score.txt'

f = open(filename,'r', encoding='UTF-8')
line = f.readline()
while line:
    print(line, end='')
    line = f.readline()

f.close()

  场景二: 处理文件与路径标准库libpath

#!/usr/bin/env python
from pathlib import Path

log_dir = Path("logs/")
log_file = log_dir / "path.log"
fb = open(log_file)
print(log_file.read())

请注意两点:

  • 在pathlib中请直接用正斜杠(“/”)。Path对象可以将正斜杠转换成当前操作系统应该使用的正确斜杠。Nice!
  • 如果想在某个Path对象后添加内容,只要在代码里使用“/”操作符(也就是除号!?)。跟一遍又一遍地敲os.path.join(a, b)的日子说拜拜吧!

我们可以不用调用open()或者close()之类的函数,而直接读文件的内容   

log_dir = Path("logs/")
log_file = log_dir / "path.log"

print(log_file.read_text())

  常见问题:

    1. UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 

              解决:  指定utf8字符集进行读取,  打开文件的时候,设置字符集 encoding='utf-8'

原文地址:https://www.cnblogs.com/xingxia/p/python_file.html