Reading and Writing
Mike Meyer
mwm at mired.org
Fri Dec 24 06:39:52 EST 2004
Sir Galahad the chaste <sttmjoc0 at fastmail.fm> writes:
> Hi,
>
> elias.goodman at gmail.com wrote:
>> How should I: Open a Text file, read from it, modify it, print to
>> another .txt?
>> For instance: Read a string, sort it, write the sorted string.
>
> What do you mean by "sorting"? If you want to sort the lines contained
> in a file, you could do something like this.
>
> $ cat in.txt
> foo
> bar
> baz
> ham
> spam
> $ cat process.py
> #!/usr/bin/env python
> lines = open("in.txt").readlines()
Some people consider it bad style to leave opened files lieing around,
so this shold be:
f = open("in.txt")
lines = f.readlines()
f.close()
> lines.sort()
> out = open("out.txt", "w")
> for line in lines:
> out.write(line)
Those two should be
out.writelines(lines)
> out.close()
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list