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

G

Gilles

Hello

This is a newbie question.

I need to read a text file into a variable, loop through each line and
use a regex to substitute some items within the line, and save the
whole variable into a new text file.

This triggers an error when I save the modified variable that contains
all the lines:
==================
import re,sys

f = open("C:\\input.txt", "r")
textlines = f.readlines()
f.close()

for line in textlines:
#edit each line
line = "just a test"

#rewrite data to new file
log = open('output.sub','w')
#ERROR: argument 1 must be string or read-only character buffer, not
list
log.write(textlines)
log.close()
==================

Should I use another way to read the file, edit each line, and save
the data into a new file?

Thank you.
 
G

Gilles

(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()
 
T

Terry Reedy

(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())
 
G

Gilles

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:

Thanks guys for the suggestion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,818
Messages
2,569,732
Members
45,691
Latest member
Dick331194

Latest Threads

Top