'ValueError: embedded null byte when opening a file using bytestring Python
I try to open a file (here bytestring is shortened) but get ValueError: embedded null byte
My code:
file = b'\x03\x04\x14\x00'
with open(file) as f:
print(f.name)
I get this:
ValueError: embedded null byte
Solution 1:[1]
Here's your code; let's go through it. I see three issues.
file = b'\x03\x04\x14\x00'
with open(file) as f:
print(f.name)
The
open(file)
requires a filename or path, not bytes.Your
file
is actually the bytes you'd get from runningf.read()
, after opening the file.Finally, in
f.name
, the "name" is probably a "property" of a filePath
(i.e.from pathlib import Path
).
Typically, the pattern would look more like this:
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_)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sean McCarthy |