1

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
5
  • It's not the whole bytestring, original bytestring is super long because it's an excel file and it has hundreds of null bytes Commented Jul 21, 2021 at 11:54
  • 1
    So this bytestring isn't a file name? Why are you using open on it at all? Are you trying to pass the actual bytes contained in the file? This sounds like an XY problem. What are you trying to do? Commented Jul 21, 2021 at 11:59
  • I'm sending a file in bytes format to a server, server receives a file (bytes) and should extract the file name. One of the options is to use this: with open(bytes) as f: name = f.name Commented Jul 21, 2021 at 12:06
  • Perhaps you could try mode = 'rb' in open, though if these bytes are the whole file rather than the name of the file, I don't think it really makes sense. Commented Jul 21, 2021 at 12:26
  • mode = 'rb' did not help Commented Jul 21, 2021 at 13:18

1 Answer 1

5

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)
  1. The open(file) requires a filename or path, not bytes.

  2. Your file is actually the bytes you'd get from running f.read(), after opening the file.

  3. Finally, in f.name, the "name" is probably a "property" of a file Path (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_)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.