使用情景
使用python读取文本文件的时候,经常会碰到报错的情况。大体的原因就是文件的编码不对。我们可以读取的时候加上文件的编码,但是万一下一个文件,又遇上不同的编码呢?这时候又会报错了。于是想到做一个通用的python文件读取程序,读取不同编码的文件。
思路与使用技术
读取文本文件时,并不知道文本文件的编码,所以采用这种方法来确认编码:
chardet.detect(text).['encoding']
读取文件的时候,采用第二个参数为:‘rb’ ,以二进制格式打开一个文件用于只读。这就避免了指定了encoding与文件实际编码不匹配而报错的问题
with open(filename, 'rb') as f:
file_text = f.read()
由于在实际使用的过程中,经常会碰到按行读取的情况,这时候就可以做一下处理,根据“\n"进行拆分,然后再重组列表,就可以还原了。
代码
本代码实现两个功能:
1、读取全部文本到一个变量中
2、按行读取文件文本,存入一个列表中。
import chardet
def check_code(text):
adchar = chardet.detect(text)
if adchar['encoding'] == 'gbk' or adchar['encoding'] == 'GBK' or adchar['encoding'] == 'GB2312':
true_text = text.decode('GB2312', "ignore")
elif adchar['encoding'] == 'UTF-8-SIG':
true_text = text.decode('utf-8-sig', "ignore")
else:
true_text = text.decode('utf-8', "ignore")
return true_text
def read_text_file(filename):
try:
with open(filename, 'rb') as f:
file_text = f.read()
file_text = check_code(file_text)
return file_text
print("读取文本文件成功%s" % (file_url))
except Exception as e:
raise e
def read_text_file_readline(filename):
result = []
text = read_text_file(filename)
textresult = text.split("\n")
for t1 in textresult:
t1 = t1 + "\n"
result.append(t1)
return result
if __name__ == "__main__":
filename = 't0001.txt'
result1 = read_text_file(filename)
result2 = read_text_file_readline(filename)
print("result1=", result1)
print("result2=", result2)