[2.5.1] Read each line from txt file, replace, and save?

Terry Reedy tjreedy at udel.edu
Sun Sep 2 14:04:29 EDT 2012


On 9/2/2012 6:36 AM, Gilles wrote:
> On Sun, 02 Sep 2012 12:19:02 +0200, Gilles <nospam at nospam.com> wrote:
> (snip)
>
> Found it:
>
> #rewrite lines to new file
> output = open('output.txt','w')
>
> for line in textlines:
> 	#edit each line
> 	line = "just a test"
> 	output.write("%s" % line)
>
> output.close()

If you process each line separately, there is no reason to read them all 
at once. Use the file as an iterator directly. Since line is already a 
string, there is no reason to copy it into a new string. Combining these 
two changes with Mark's suggestion to use with and we have the following 
simple code:

with open('input.txt', 'r') as inp, open('output.txt', 'w') as out:
     for line in inp:
         out.write(process(line))

where for your example, process(line) == 'just a test\n'
(you need explicit line ending for .write())

-- 
Terry Jan Reedy




More information about the Python-list mailing list