[Numpy-discussion] NOOB Alert: Looping Through Text Files...

Zachary Pincus zachary.pincus at yale.edu
Fri Jan 14 19:09:38 EST 2011


> textlist = ["test1.txt", "test2.txt", "test3.txt"]
>
> for i in textlist:
> 	text_file = open(textlist, "a")
> 	text_file.write("\nI suck at Python and need help")
> 	text_file.close()
>
> But, this doesn't work.  It gives me the error:
>
> coercing to Unicode: need string or buffer, list found

Yeah, it's probably the wrong list; still, easy enough to answer...

You want this:
   text_file = open(i, "a")

to open the individual file, as opposed to:
   text_file = open(textlist, "a")

which tries to open the whole list of filenames. Python cannot figure  
out how to turn the list into a single (unicode) filename, hence the  
error.

As for your wanting to write files with new names:

for txtfile in txtlist:
   f = open(txtfile, 'r')
   data = f.read()
   f.close()
   fnew = open(get_new_name(txtfile), 'w')
   fnew.write(data)
   fnew.write('\nHelp is on the way.')
   fnew.close()

where get_new_name() or whatever is defined appropriately to transform  
the old name ('test1.txt', say) into 'test1_appended.txt'...

Zach





More information about the NumPy-Discussion mailing list