1

I'm trying to use the struct.pack so I can write a string into a file. When I do, I get the following error:

File "----", line 166, in main
struct.pack('>256s', *master_header)
struct.error: pack expected 1 items for packing (got 256)

Now, reading from here I seem to be using it right. I specify that I'm getting 256 bytes/characters in my string.

I'm using version 3.3.3.

3
  • Why do you add the *? Commented Feb 12, 2014 at 11:15
  • "so I can write a string into a file" - as in, you have a string, and you want to write it to a file, or you have something else, and you want to make it a string so you can write it to a file? Commented Feb 12, 2014 at 11:27
  • I have a 256 byte string I want to pack into a binary string using struct.pack. Commented Feb 12, 2014 at 22:24

1 Answer 1

1

The documentation says:

For the 's' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters.

So, >256s expects a single string 256 bytes long. If master_header already is such a string, just pass it to struct.pack without the *.

Using the * at the call site causes the string itself to be unpacked into its constituent characters, strings being iterable. As a result, struct.pack receives its 256 individual characters as arguments, causing the observed error.

Sign up to request clarification or add additional context in comments.

2 Comments

master_header is a single string that's 256 bytes long.
@zdc000 In that case, just lose the *.

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.