普通模式(python2、python3通用)
f = open(fileName, mode='r')
open函数在python2和python3差异点:
python3支持多个参数,python2只有2个参数,且对于文件编码不支持
#python3
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
#python2
open(name[, mode[, buffering]])
python2如何支持不同编码的文件读写?
import codecs
# 这里增加u是为了防止乱码,详见 https://blog.csdn.net/songlh1234/article/details/83791205
fileNameWrite = u'测试codecs写入gbk.txt'
fileWrite = codecs.open(fileNameWrite, 'w', "gbk")
fileWrite.write('设备编号,deviceID,ehomeKey,执行结果,返回报文\n')
另外这里需要注意,以上代码在python3下执行正常,但write这一行代码在python2下会报错:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 0: ordinal not in range(128)
需要额外设置默认字符
try:
# Python2
reload(sys)
sys.setdefaultencoding("utf-8")
except NameError:
print('NameError')
UTF-8编码方式打开文件
def openFile(path):
f = None
try:
f = open(path, encoding='UTF-8')
except FileNotFoundError:
print("open file %s error" % path)
else:
print("open file %s ok" % path)
return f
gb18030编码方式打开文件
def openFile(path):
f = None
try:
f = open(path, encoding='gb18030')
except FileNotFoundError:
print("open file %s error" % path)
else:
print("open file %s ok" % path)
return f
说明:如果不带encoding参数,会采用系统编码,Windows下默认为gbk
读取文件内容
file_name = r"D:\1.txt"
f = openFile(file_name)
for line in f:
print(line)
获取当前路径:
os.getcwd()
拼接路径和文件名
fileName1 = os.path.join(filePath, fileName)
获取文件所在的文件目录
directory_path = os.path.dirname(file_name) # 根据绝对路径,返回所在的目录
读取文件字符时遇到如下问题:
UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa6 in position 1909: illegal multibyte sequence
问题原因:文档默认使用’gbk’编码打开,但文档实际编码是gb18030,有些字符无法被gbk识别。
解决方案:打开文件的时候可以指定字符集为gb18030
f = open(path, encoding="gb18030")