By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,818 Members | 1,381 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,818 IT Pros & Developers. It's quick & easy.

write integers to txt file with .write() func in Python?

P: 3
I am trying to write a Program that takes a string and converts it to Ascii, then writes the numbers to a txt file. However when I try to use the .write() function python throws an error "TypeError: argument 1 must be string or read-only character buffer, not int"
This is an example of the code section I am trying to create:

Expand|Select|Wrap|Line Numbers
  1. print "enter string"
  2. word = raw_input()
  3.  
  4. out_file = open("code.txt","a")
  5. out_file.write("------------------------NEW-CODE--------------------\n")
  6.  
  7. for char in word:
  8.     code= ord(char)   
  9.     out_file.write(code)   #this is the error...
  10.  
  11. out_file.close()
can I use the write() func, or should I use a different function, or do i have to create my own....and if so how would I do that?
Any help greatly appreciated
Dec 18 '06 #1
Share this Question
Share on Google+
4 Replies


bartonc
Expert 5K+
P: 6,596
I am trying to write a Program that takes a string and converts it to Ascii, then writes the numbers to a txt file. However when I try to use the .write() function python throws an error "TypeError: argument 1 must be string or read-only character buffer, not int"
This is an example of the code section I am trying to create:

Expand|Select|Wrap|Line Numbers
  1. print "enter string"
  2. word = raw_input()
  3.  
  4. out_file = open("code.txt","a")
  5. out_file.write("------------------------NEW-CODE--------------------\n")
  6.  
  7. for char in word:
  8.     code= ord(char)   
  9.     out_file.write(code)   #this is the error...
  10.  
  11. out_file.close()
can I use the write() func, or should I use a different function, or do i have to create my own....and if so how would I do that?
Any help greatly appreciated
To make that work, use

>>> str(ord("a"))
'97'
>>>
to convert the ascii value into something that a text file can handle (text).
You can't mix text and binary data in a file (it's one or the other).
Dec 18 '06 #2

P: 3
thanks very much, I will see what I can do. I will be sure to let you know if I get it working. ^_^
Dec 18 '06 #3

P: 3
Got it, thanks a bunch!!!
I didn't understand that the Ascii code was not a "text number", thanks for the help.
Dec 19 '06 #4

bartonc
Expert 5K+
P: 6,596
Got it, thanks a bunch!!!
I didn't understand that the Ascii code was not a "text number", thanks for the help.
You are quite welcome. That's what this site is all about. Keep posting,
Barton
Dec 19 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.