Newbie looking for feedback
David Lees
debl.spamnono at world.std.com
Sat Sep 16 01:49:57 EDT 2000
Thanks for the help and suggestions on this one. Time to go learn how
to use "for" and the debugger.
David Lees
Jeremy Hylton wrote:
>
> David Lees <debl.spamnono at world.std.com> writes:
>
> > Two questions. First, I have written a real simple Python routine to
> > remove blank lines from a text file. The code below works but...
> >
> > 1. I am sure this can be written much more simply, any hints?
>
> > import string
> >
> > fin=open("c:\\foo.txt","r")
> > fout=open("c:\\barf.txt","w")
> > s=""
> >
> > while 1:
> > nextln=fin.readline()
> >
> > if len(nextln)==0 :
> > break
> >
> > if nextln[0] != '\n' :
> > fout.write(nextln)
> >
> > fin.close()
> > fout.close()
>
> This program does exactly what your program does:
>
> import fileinput
> f = open("c:\\bar.txt", "w")
> for line in fileinput.input("c:\\foo.txt"):
> if not line.startswith("\n"):
> f.write(line)
> f.close()
>
> If I could modify the behavior a bit, I would: (1) make it skip any
> non-blank line that only has whitespace and (2) have it edit the file
> in place.
>
> import fileinput
> for line in fileinput.input("c:\\foo.txt", inplace=1):
> if line.strip():
> f.write(line)
> f.close()
>
> -- Jeremy Hylton <http://www.python.org/~jeremy/>
More information about the Python-list
mailing list