因为各种文件的不同格式,导致导致文件打开失败,这时,我们可以先判断文件的编码吗格式,然后再根据文件的编码格式进行读取文件
举例:有一个data.txt文件,我们不知道它的编码格式,现在我们需要读取文件的编码格式:
import chardet
def get_data():
path = r
'data.txt'
f = open(path,
'rb')
# 先用二进制打开
data = f.read()
# 读取文件内容
file_encoding = chardet.detect(data).get(
'encoding')
# 得到文件的编码格式
with open(path,
'r', encoding=file_encoding)as file:
# 使用得到的文件编码格式打开文件
lines=
file.readlines()
for line
in lines:
print(line)
if __name__==
'__main__':
get_data()
转载于:https://www.cnblogs.com/shixisheng/p/11207288.html
相关资源:Python实现按特定格式对文件进行读写的方法示例