[Courses] [python] No lesson -- open discussion
Akkana Peck
akkana at shallowsky.com
Wed Aug 24 03:33:15 UTC 2011
Leslie writes:
> First, thanks for this excellent course!
You're welcome! You've been a great student.
On your file I/O question:
> >>> mylist = ["This is line 3 of my file.\n", "This is line 4 of my file.\n"]
I agree with Andreas that I probably wouldn't include the \n in each
line, and just add that in when writing to the file.
> >>> f = open("myfile.txt", "a")
> >>> for i in mylist:
> ... f.write(i)
> ...
> >>> f.close()
> >>> x = subprocess.Popen(["cat","myfile.txt"], stdout=subprocess.PIPE)
> >>> for line in x.stdout:
> ... print line
I may be missing something, but when reading back from the file,
after finishing your writes and closing the file, can't you just
open the file for reading normally? I'm not sure what adding the
cat process gets you.
f = open("myfile.txt", "r")
for line in f :
print line
f.close()
> Although it works, I am not sure this is the best way to add lines from
> a list. And if I wanted to append one file to another, is there a
> straightforward way?
Your appending code looks fine, but I probably should mention that
there's yet another way. (Pythonistas make fun of Perl's TIMTOWTDI
-- pronounced "tim toady" and standing for "There Is More Than One
Way To Do It" -- but Python often has a lot of ways too.)
The print statement can take an optional file argument, so you could
do something like this:
f = open("myfile.txt", "a")
for i in mylist:
print >>f, i
f.close()
That's not necessarily any better than what you did, and often it's
better to use write() because you get better control if you need
to write less than a line at a time. But it's available if you ever
have a situation where print is more convenient to use than write.
And in the spirit of "more than one way to do it", Andreas's join
idea is yet another way that also works fine. I probably wouldn't
use the join myself in this case because I find it a little easier
to read as a loop, but that's just personal preference, and I do
like using join in a lot of other places.
...Akkana
More information about the Courses
mailing list