2015-11-28 218 views
5

我在学院学习python,但我坚持使用我当前的任务。我们应该采取2个文件并进行比较。我只是试图打开文件,这样我可以使用他们,但我不断收到错误"ValueError: embedded null character"当使用open()时出现“ValueError:embedded null character”

file1 = input("Enter the name of the first file: ") 
file1_open = open(file1) 
file1_content = file1_open.read() 

这个错误是什么意思?

+0

哪里文件来自哪里? –

+0

我的老师在运行程序时添加了要使用的测试仪文件。其中一个测试人员给我的错误的第一个文件是“Tests/4-test.txt” – Erica

+0

你有一个空字节嵌入在字符串中不会使用python,你需要删除空字节/ s 。你在使用什么操作系统? –

回答

2

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() 
+0

我不允许将任何东西导入到我的程序中 – Erica

相关问题