Jump to content

  • Log In with Google      Sign In   
  • Create Account

Write int to file in python


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 hahaha   Members   -  Reputation: 100

Like
0Likes
Like

Posted 24 September 2007 - 11:30 PM

I want to write an int to a file instead of a char so my cpp program can read it easier. So say for example i have something like this in python:
Out = open("123.txt","w")
Out.write(24)
Out.close()

I get this error:
Traceback (most recent call last):
  File "123.py", line 2, in <module>
    Out.write(24)
TypeError: argument 1 must be string or read-only character buffer, not int
To get it to work i have change Out.write(24) to Out.write(str(24)). That way it writes a char to the file. Is there a way in python to write an int to a file? Thanks

Sponsor:

#2 let_bound   Members   -  Reputation: 488

Like
0Likes
Like

Posted 25 September 2007 - 12:18 AM

Do you want to write the string representation of an integer to a text file, as your code suggests ("123.txt" and "w" mode instead of "wb"), or do you want to write the binary representation of an integer to a binary file? My question is meaningless if you're on a non-Microsoft system, but I had to ask, because the .txt extension is confusing.

In the first case, it's easy (there might be an even easier way, but I'm no Python expert), as you've found out yourself:


out = open("123.txt", "w")
out.write(str(24))
out.close()



In the second case, you'll have to use the struct module, IIRC:


import struct
out = open("123.bin", "wb") # note: 'b' for binary mode, important on Windows
format = "i" # one integer
data = struct.pack(format, 24) # pack integer in a binary string
out.write(data)
out.close()



Reading back from the file:


import struct
input = open("123.bin", "rb")
data = input.read()
input.close()
format = "i"
value, = struct.unpack(format, data) # note the ',' in 'value,': unpack apparently returns a n-uple




#3 hahaha   Members   -  Reputation: 100

Like
0Likes
Like

Posted 25 September 2007 - 12:35 AM

Original post by let_bound


import struct
out = open("123.bin", "wb") # note: 'b' for binary mode, important on Windows
format = "i" # one integer
data = struct.pack(format, 24) # pack integer in a binary string
out.write(data)
out.close()




I just want to know why you used i as the value of format? If i change it it gives me some or other bad value error

Edit: Sorry i read the link you gave and i realize why now.

Thanks a lot




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS