CMSC 201

Lab 9: File I/O

File I/O

In this lab, you will be working on reading from and writing to a file. There are times when you will need to output work to a file or when you will need to read in values that would be unreasonable for the user to enter.


Opening a File:

file = open("filename",'r')

Let's look at each part individually. First, you have to pass in the file name as a string. You can do this by hardcoding it or by using a variable. This means that this code will work:

fileName = "name"
file = open(fileName, 'r')

This string is case sensitive and requires an extension if the file has one. If your file name is "fileName.txt" make sure to includ the .txt in your string. If the file is in a different folder, you will need to use a path.

The second value is the way you are opening the file. In the case of the example, you are opening it in "read" mode, so you can read from it. All possible modes are:
read - 'r'
append - 'a'
write - 'w'
read and write - 'r+'

Append mode will write to the file starting from the end. Write mode will clear all contents from a file and start writing from the beginning. Read and write will not clear the contents but, if you try to write, it will write at the beginning of the file, overwriting everything inside it character by character. If you do not provide a second argument, the file will be opened in read mode automatically.

Reading From a File

file = open("filename",'r')
for line in file:
    print(line)
file.close()

The above code will print each line in the file one at a time.

f.read()
f.readline()

The above lines of code are another way to read from the file. read() will read the entire file and return its contents as a string. readline() works much like the for loop in the previous example, reading one line at a time. readline() strings always end in '\n' so if you get an empty string you know you are done with the file.

Writing To a File

file = open("fileName",'w')
file.write("Test string")
file.close()

write() is used whether you opened in write or append mode. It simply writes whatever string you pass it to the file. You may only pass it a string.

Remember to close the file when you are done using it. Once it is closed, if you want to access it again you will have to call open() on it, even if you still have access to the variable you stored it to.