Basic I/O

To read and write into a file, you need to first open the file which creates a file object. The method open takes two arguments: the first is the name of the data file that you want to open; the second is the mode with "w" = write and "r" = read.

If you open a file for writing , it will either create a file of that name if it doesn't exist or it will replace a file by that name (subsequently, you should be careful not to open a file that you don't want to replace).

f = open("test.dat", "w")

To open a file for reading , the file needs to exist already, otherwise you will get an error:

f = open("testDNE.dat", "r")

To put data into a file that you've opened for writing, you can use the write command which takes a string as an argument. To get the right formatting, you will often make use of carriage returns ("\n") or text delimiters like ("\t").

f.write("Welcome to my mod columns\n")
f.write("i \t %2 \t %3 \t %4 \n")
for i in range(20):
	f.write(str(i) + "\t" + str(i%2) + "\t" + str(i%3) +"\t" + str(i%4)+"\n")

Closing the file indicates that we are done using (in this case, writing into) the file and can be made available for reading.

f.close()

Now that we've created this file and closed it, we now open it to read the file. In using any of the read methods to read data from the file, it is very important to understand that where the reading will begin is always where you last left off unless you close the file, in which case the reading will start from the beginning of the file.

f = open ("test.dat", "r") 
 
# it can take an argument of the number of characters to be read
content = f.read(5)
print "First 5 characters are:", content
 
# now notice that if I keep on reading, it will only start at the place I just left off
content = f.read(10)
print "Next 10 characters are:", content
 
#Similarly, you can read one line at a time, which starts from where I left
#off and outputs everything from that point to the nearest carriage return
content = f.readline()
 
# if you want to start all over and read from the beginning, you have to close the file and
# reopen it
f.close()
f = open("test.dat", "r")
# Now if no arguments are supplied, then the entire text is read
contentAll = f.read()
print contentAll