ValueError:使用字节串Python打开文件时嵌入了null字节



我试图打开一个文件(这里字节串被缩短(,但得到ValueError:嵌入的空字节

我的代码:

file = b'x03x04x14x00'
with open(file) as f:
print(f.name)

我得到这个:

ValueError: embedded null byte

这是您的代码;让我们复习一下。我看到三个问题。

file = b'x03x04x14x00'
with open(file) as f:
print(f.name)
  1. open(file)需要文件名或路径,而不是字节。

  2. file实际上是在打开文件后运行f.read()得到的字节。

  3. 最后,在f.name中;name";可能是";属性";文件CCD_ 5(即CCD_。

通常,模式看起来更像这样:

from pathlib import Path
file = Path("/home/user/docs/spreadsheet.csv")
print(file.name)
# Open file in "read-binary" mode, and read all the content into the "bytes_" variable
with open(file, 'rb') as f:
bytes_ = f.read()
print(bytes_)

最新更新