It may be interesting to know that there is a subtle, yet important difference between:
file = open( filename )
lines = file.readlines()
for line in lines:
do something
and
file = open( filename )
for line in file:
do something
The first solution (with readlines
) will load the whole contents of the file in memory and return a python list (of strings). On the other hand, the second solution makes use of something that's called a iterator
. This will in fact move the pointer in the file as needed and return a string. This has an important benefit: The file is not loaded into memory. For small files, both approaches are OK. But as long as you only work with the file line-by-line, I suggest to use the iterator behavior directly.
So my solution would be:
infile = open( filename )
outfile = open( "%s.new" % filename, "w" )
for line in infile:
outfile.write( line[2:] )
infile.close()
outfile.close()
Come to think of it: If it's a non-ascii file (for example latin-1 encoded), consider using codecs.open. Otherwise you may have a nasty surprise as you may accidentally cut a multibyte character in half ;)
However, if you don't need python, and the only thing you need to do is crop the first two characters from the file, then the most efficient way to do it is kch's suggestion and use cut
:
cat filename | cut -d2- > newfile
For these kinds of quick-and-dirty file operations I always have cygwin installed on my non-linux boxen. But I believe there's a set of windows binaries for these tools as well which would perform faster than in cygwin iirc.