I found an odd problem with Python's struct.pack("!i", 10)
on a Windows system. I get the buffer and save it in to a file, but the result is
00 00 00 0d 0a
where on Mac OSX, the result is
00 00 00 0a
What does the 0d
mean?
When I pass 11
instead of 10
, the result is 00 00 00 0b
. So I think when I pass 10
, the result should be 00 00 00 0a
.
If I want to get 00 00 00 0a
when I pass 10
, what should I do instead?
What does the
0d
mean?
It means '\r'
If I want to get
00 00 00 0a
when I pass10
, what should I do instead?
Try to open file in binary mode:
with open('file', 'wb') as f:
f.write(struct.pack("!i", 10))
When you try write '\n'
(0a
) to a file on Windows and the file is opened in text mode, Python adds '\r'
before '\n'
.
From documentation:
In text mode, the default is to convert platform-specific line endings (
\n
on Unix,\r\n
on Windows) to just\n
on reading and\n
back to platform-specific line endings on writing. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that inJPEG
orEXE
files. Be very careful to use binary mode when reading and writing such files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With