Writing to files

Bjorn Pettersen bjorn at roguewave.com
Mon Mar 20 18:33:41 EST 2000


"Daley, MarkX" wrote:
> 
> Daley, MarkX wrote:
> 
> > Here is a piece of code I wrote to write the items in a list sequentially
> to
> > a file.
> >
> > Definitions:
> >
> > a=some list ([1,2,3,whatever])
> > f=open('filename','a')
> >
> >       for x in a:
> >               f.write(a[x])
> >
> > When I run it, I get this:
> >
> >       Traceback (innermost last):
> >                File "<pyshell#2>", line 1, in ?
> >                collect.collect()
> >       File "C:\PROGRA~1\Python\collect.py", line 30, in collect
> >               f.write(a[x])
> >       TypeError: sequence index must be integer
> 
> Of course. The first thing you want is:
>         for x in a:
>                 f.write(x)
> 
> at least until you discover that write wants a string (which may
> be binary).
> 
> > Any ideas on what is causing this?  The data in the list is columnar
> > information pulled from a database, but this shouldn't be the cause of the
> > problem because I can substitute a print statement in for the f.write
> > statement and it works just fine.  Any suggestions are appreciated.
> 
> No, "print a[x]" would have the same problem. "print x"
> wouldn't, but it automatically converts x to a string if it's not
> one already.
> 
> - Gordon
> 
> I didn't realize print converts to a string.  I guess the question I should
> ask then, is how do I write a list to a file item by item?
> 
> -  Mark

Your question is really, "how do you convert items in a list to
strings"?

If you know they're strings allready, you can just write them out:

	mylist = ['a','b','c']
	f = open('foo.txt', 'w')
	for item in mylist:
	    f.write(item + '\n') # add a newline..

If you don't know that they're strings, you must convert them.  You can
do this in three different ways:

	`item`		# back tics (this calls repr for you)
	repr(item)	# call repr yourself
			# for built-in types this gives a 
			# representation that closely resembles
			# the way you would write it using Python
			# code.
	str(item)	# call str.
			# this can give a more human readable 
			# representation, but will in many cases
			# just default to repr.

In code it would look like:

	mylist = [1,2,3]
	f = open('foo.txt', 'w')
	for item in mylist:
	    f.write(`item` + '\n')
	    f.write(repr(item) + '\n')
	    f.write(str(item) + '\n')

Hope this helps.

-- bjorn




More information about the Python-list mailing list