Reading a file and then writing something back

Byron DesertLinux at netscape.net
Wed Jul 21 13:50:15 EDT 2004


Hi Kevin,

Even though I am fairly new to Python, it appears that you might of 
found a bug with 'r+' writing / reading mode.

Here's a couple of suggestions which you might find helpful:

1) To make your programs faster and less 'error'-prone, you might want 
to read the text file into memory (a list) first, like this:

	f = open("c:/test.txt", "r")
	names = f.readlines()			# Read all lines in file and store data in a list.
	for name in names:			 # Display a listing of all lines in the file.
		print name
	f.close()					      # Close the text file (we'll change it later).


2) When you want to add new names to the "text file" (in memory), you 
can easily do so by doing this:

	names = names + ["William\n"]			# Adds William to the list (text file 
in memory).
	names = names + ["Steven\n"]			 # Adds Steven to the list.
	names = names + ["Tony\n"]			  # Adds Tony to the list also.


3) If you wish to sort the list in memory, you can do this:

	names.sort()								# Places the names in the list now in ascending 
order (A - Z).


4) Finally, to re-write the text file on the disk, you can do this:

	f = open("c:/test.txt", "w")			# Re-write the file from scratch with 
revised info.
	for name in names:				      # For each name that is in the list (names)
		f.write(name)					    # Write it to the file.
	f.close()							   # Finally, since the file has now been 100% 
rewritten with new data, close it.


--------------

Why does this have advantages?  Several reasons, which are:

1) It does the processing in the memory, which is much quicker.  Faster 
programs are always a nice feature!
2) It allows for additional processes to occur, such as sorting, etc.
3) It reduces the chances of "having a disk problem."  One simple read & 
  one simple write.


Hope this helps,

Byron
---



More information about the Python-list mailing list