[Tutor] in as a stream, change stuff, out as a stream?
Remco Gerlich
scarblac@pino.selwerd.nl
Thu, 12 Jul 2001 06:13:40 +0200
On 0, Israel Evans <israel@lith.com> wrote:
> At any rate, I was wondering if it would be possible to read a line, change
> it in the same file I'm reading and move on to the next line, when I'm done.
> Is this possible? Or should I read everything at once, change the name of
> the old file and write everything out to a file with the same name as the
> old one.
The fileinput module is a high level layer over things like this. You can
use it to read files line by line (it won't read it all into memory at once)
and your output goes back to the file (that is, it renames the old file to a
.bak file, and sends the output to a new file - then deletes the backup, by
default).
Something like:
import fileinput
files = [...list of filenames...]
def process_line(line):
# Do something with a line, print the result
for line in fileinput.FileInput(files, inplace=1):
process_line(line)
--
Remco Gerlich