text file edit object

Batista, Facundo FBatista at uniFON.com.ar
Fri Jul 11 08:34:48 EDT 2003


#- Not to mention the fact that you can't write to myfile as 
#- defined. ;-)  How
#- about something like (not tested):

Jajaja, sorry. Very stupid, didn't open the file for writing, :p



#-     import os, sys
#- 
#-     try:
#-         infile = file("foo.txt", "r")
#-         lines = infile.readlines()[:-10]
#-         infile.close()
#-     except IOError:
#-         print >> sys.stderr, "edit failed"
#-     else:
#-         try:
#-             outfile = file("foo.txt.new", "w")
#-             outfile.writelines(lines)
#-             outfile.close()
#-         except IOError:
#-             try:
#-                 os.unlink("foo.txt2")
#-             except IOError:
#-                 pass
#-             print >> sys.stderr, "edit failed"
#-         else:
#-             os.rename("foo.txt2", "foo.txt")
#- 

What about something like this:

try:
	infile = file("foo.txt", "r")
	lines = infile.readlines()[:-10]
	infile.close()
	outfile = file("foo.txt.new", "w")
	outfile.writelines(lines)
	outfile.close()
except:
	print >> sys.stderr, "edit failed"
	raise
else:
	os.rename("foo.txt2", "foo.txt")


One question: is this method (file, readlines) efficient on big files?





More information about the Python-list mailing list