使用OPEN()时出现“ValueError:Embedded Null Character”

hec6srdp  于 2022-10-02  发布在  Python
关注(0)|答案(9)|浏览(418)

我在我的大学里学了Python课程,现在的任务让我束手无策。我们应该拿出两份文件进行比较。我只是想打开文件,以便可以使用它们,但我一直收到错误"ValueError: embedded null character"

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

这个错误是什么意思?

bksxznpy

bksxznpy1#

对于以下代码,我也收到了相同的错误:

with zipfile.ZipFile("C:local_filesREPORT.zip",mode='w') as z:
    z.writestr(data)

之所以会发生这种情况,是因为我正在传递writestr()方法中的bytestring即数据,而没有指定应该保存它的文件名,即Report.zip。所以我更改了我的代码,它起作用了。

with zipfile.ZipFile("C:local_filesREPORT.zip",mode='w') as z:
    z.writestr('Report.zip', data)
hrirmatl

hrirmatl2#

如果您尝试打开文件,则应使用os生成的路径,如下所示:

import os
os.path.join("path","to","the","file")
eaf3rand

eaf3rand3#

看起来您在字符“\”和“/”方面有问题。如果您在输入中使用它们-尝试将一个更改为另一个...

8ehkhllq

8ehkhllq4#

Python3.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"xEFxBBxBF"):  # UTF-8 with a "BOM"
        return "utf-8-sig"
    elif data.startswith(b"xFFxFE") or data.startswith(b"xFExFF"):
        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()
k3fezbri

k3fezbri5#

将文件复制到以数字开头的文件夹时出现此错误。如果在数字前写上双\号的文件夹路径,问题就解决了。

i1icjdpr

i1icjdpr6#

在Windows上指定文件名的完整路径时,应该使用双反斜杠作为分隔符,而不是单反斜杠。例如,C:\FileName.txt代替C:\FileName.txt

jum4pzuy

jum4pzuy7#

该问题是由于需要解码的字节数据造成的。

当您将一个变量插入到解释器中时,它显示它的epr属性,而print()接受str(在这个场景中是相同的),并忽略所有不可打印的字符,如:\x00,\x01,并用其他字符替换它们。

一种解决方案是“解码”file1_content(忽略字节):

file1_content = ''.join(x for x in file1_content if x.isprintable())
cbjzeqam

cbjzeqam8#

文件路径名的第一个斜杠将引发错误。

需要原始数据,r
原始字符串

FileHandle = open(r'..', encoding='utf8')

FilePath=‘C://FileName.txt’
FilePath=r‘C:/FileName.txt’

lf5gs5x2

lf5gs5x29#

尝试将r(原始格式)放入。

r'D:python_projectstemplates0.html'

相关问题