Python 3.5文件的缺省编码是'utf-8'。
用于Windows的文件的默认编码往往是别的。
如果你打算开两个文本文件,可以试试这个:
import locale
locale.getdefaultlocale()
file1 = input("Enter the name of the first file: ")
file1_open = open(file1, encoding=locale.getdefaultlocale()[1])
file1_content = file1_open.read()
应该有标准库的一些自动检测。
否则你就可以创造自己的:
def guess_encoding(csv_file):
"""guess the encoding of the given file"""
import io
import locale
with io.open(csv_file, "rb") as f:
data = f.read(5)
if data.startswith(b"\xEF\xBB\xBF"): # UTF-8 with a "BOM"
return "utf-8-sig"
elif data.startswith(b"\xFF\xFE") or data.startswith(b"\xFE\xFF"):
return "utf-16"
else: # in Windows, guessing utf-8 doesn't work, so we have to try
try:
with io.open(csv_file, encoding="utf-8") as f:
preview = f.read(222222)
return "utf-8"
except:
return locale.getdefaultlocale()[1]
然后
file1 = input("Enter the name of the first file: ")
file1_open = open(file1, encoding=guess_encoding(file1))
file1_content = file1_open.read()
哪里文件来自哪里? –
我的老师在运行程序时添加了要使用的测试仪文件。其中一个测试人员给我的错误的第一个文件是“Tests/4-test.txt” – Erica
你有一个空字节嵌入在字符串中不会使用python,你需要删除空字节/ s 。你在使用什么操作系统? –