Python读写文件的编码格式-UTF-8, GBK
做一个测试脚本,从文件夹A遍历所有的.txt格式文件,并打开文件逐行读取内容,写入到文件夹B里面。我们看读和写文件格式在是否指定为UTF-8时会发生什么错误。新建6个文件,汉字内容是“你好!”, 英文字符是"Hello"
代码如下
#coding=utf-8
#coding=gbk
import os
RootDir = R"E: 2_PythonToolsFold-2A\"
TargetDir = R"E: 2_PythonToolsFold-2B\"
def mkdir(path):
path=path.strip()
path=path.rstrip("\")
isExists=os.path.exists(path)
if not isExists:
os.makedirs(path)
def del_file(path):
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
del_file(c_path)
else:
os.remove(c_path)
def list_all_files(rootdir):
_files = []
list = os.listdir(rootdir)
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files
**********************************************************************************
BEGIN
**********************************************************************************
del_file(TargetDir)
_fs = list_all_files(RootDir)
for i in range (0,len(_fs)):
filepath = os.path.dirname(_fs[i])
filename = os.path.basename(_fs[i])
(shotname,extension) = os.path.splitext(filename);
filepath_new=TargetDir+\+filepath.split(:)[-1]
mkdir(filepath_new)
**fr=open(_fs[i],r)
fw=open(filepath_new+\+filename+"_tt",w)**
s="YES"
print(_fs[i])
while s!="":
s=fr.readline()
#s.decode("utf8","ignore")
fw.writelines(s)
fr.close()
fw.close()
- 不指定文件编码格式
fr=open(_fs[i],r) fw=open(filepath_new+\+filename+"_tt",w)
运行错误:UTF-8汉字读错误
- 仅指定读文件格式为UTF-8
fr=open(_fs[i],r,encoding=utf-8) fw=open(filepath_new+\+filename+"_tt",w)
运行错误:UTF-8乱码写错误
3.指定读写文件格式都为UTF-8
fr=open(_fs[i],r,encoding=utf-8) fw=open(filepath_new+\+filename+"_tt",w,encoding=utf-8)
运行错误: ANSI格式汉字读错误 测试结果:
- 对于纯英文文本文件,无论文件本身是什么格式,py也不需指定读写格式,都能正确处理
- 当文件本身是UTF-8格式,且py指定读写格式都为UTF-8时,无论文件内容是英文,汉字,还是乱码都能正确读写
- 无论文件是什么格式,当py指定读格式为UTF-8时,无论文件内容是英文,汉字,都能正确读出。
总结:
- 用Python读文本文件或写一个新的文本文件时,应该指定为UTF-8格式。
- 用Python读非UTF-8格式的文本文件前,应该先转换成UTF-8格式。
