eskandari wrote:
On May 31, 12:30 pm, MRAB <pyt...@mrabarnett.plus.com> wrote:
eskandari wrote:
Hi,
I am a newbie in python. I have an data.pickle file which is
serialized form of an "array of strings", I want to write their
offsets in another binary file, so an C++ program can read and analyse
them.
But when I try to write offset (number) in binary file, it raise
exception below in line  "offsetfile.write(offset)"
"TypeError: argument 1 must be string or read-only buffer, not int"
I search the internet, find that all suggest converting number to
string ---with str()---and then write string to file.
But I shouldn't do this. because the above mentioned C++ function,
read file with this assumption that there are numbers in file.
So I want to know, Is there any way to produce an binary file
containing numbers same as the way C++ does?
Can anybody help me?
You can't write ints to a file, but you can write bytestrings ('str' in
Python 2, 'bytes' in Python 3).

Use the 'struct' module to convert the int to a bytestring, and remember
to open the file as a binary file.

Thanks alot,
I have an question, if I do so, Will the second program (C++ program)
which process this file, encounter any problem while parsing the file?
It find number of integers by filelen/4 and ..... (It assumes that
file was created as the same way which C++ does)
Thanks in advance

You talk as if C++ has a single way to write a file, or read a file. It has dozens of possibilities, as does Python. In another message, you refer to four bytes per number, so it's possible you're talking about reading directly from the file into an int variable. If you know that the C++ program is reading a file in mode 'b' directly to an unsigned int, and is compiled in 32 bits, and has the same endian-ness as the Python program, chances are the struct will work correctly, if you're running Python under the same conditions.

DaveA
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to