[Courses] [python] No lesson -- open discussion
Leslie
leslie.brothers at verizon.net
Thu Aug 25 03:06:36 UTC 2011
On Tue, 2011-08-23 at 20:33 -0700, Akkana Peck wrote:
> On your file I/O question:
> >>> 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?
That is what I should have done. But, being a rank beginner, I only
knew about "a" -- I didn't know about "w" or "r". I have to admit it.
At that moment in time, it was the only way I could think of to print
out the file.
> I'm not sure what adding the
> cat process gets you.
As luck (and ignorance) would have it, it got me an intervention from
Andreas, who introduced me to the beauties of "r", as well as the
invaluable f.seek(0). The gain in knowledge outweighs my embarrassment.
>
> f = open("myfile.txt", "r")
> for line in f :
> print line
> f.close()
Yes, this normal way is much better.
> > 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?
> 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 great. I like it.
I am trying to get good at manipulating files in python. My next
objective: to delete one line of a file. From my researches on the web,
it looks like you have to do it indirectly, by writing the lines you
want to keep to a "good" file. Here is an example:
>>> f = open("myfile.txt", "r")
>>> for l in f:
... print l
...
This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is a goofy line.
>>> f.seek(0)
>>> f.close()
>>> inp = open("myfile.txt", "r")
>>> badf = open("badmyfile.txt", "w")
>>> goodf = open("goodmyfile.txt", "w")
>>> lines = inp.readlines()
>>> for l in lines:
... if "goofy" in l:
... badf.write(l)
... else:
... goodf.write(l)
...
>>> goodf.close()
>>> badf.close()
>>> inp.close()
>>> f = open("goodmyfile.txt", "r")
>>> for l in f:
... print l
...
This is line 1.
This is line 2.
This is line 3.
This is line 4.
Is this in fact the best way to get rid of a line?
Thanks,
Leslie
> _____________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses
More information about the Courses
mailing list