Python For GCSE
To make things easier for yourself when working with files, place the text file that you want to read in the same folder as the Python program that needs to read it.
Making The Connection
The first thing we need to do to work with a file is to open it.
f = open("myfile.txt", "r") # do things with the file f.close()
The 'r' in this example means to open the file in read mode. This would prevent us from making any changes to the contents of the file. When we open a file, we have the following options for the mode,
- r - read only
- w - write
- a - append
- r+ - read and write
When we finish working with a file, we must make sure to close it.
ReadingWe have two ways to read from a file.
f = open("myfile.txt", "r") # read the entire file a = f.read() print(a) f.close()
The other option is,
f = open("myfile.txt", "r") # read the file a line at a time for line in f: print(line) f.close()
The second option is often the one that is more useful to us. We can process the lines we read from the file as we read them. The problem we get is that the linebreaks are read alongside the data. The two methods shown above produce slightly different output.
Reading Lines Into A List
One approach I like is to use a function to read the whole file into a list. I then remove the line breaks. This leaves with me a list of the lines in the file that I can work with easily in the program.
def read_file(f): # open the file thefile = open(f,"r") # read the whole file into the list rows = [line for line in thefile] # close the file thefile.close() # remove the line break at the end of each list item for i,r in enumerate(rows): rows[i] = r.replace("\n","") return rows data = read_file("myfile.txt") print(data)
Writing To The File
Writing to the file is pretty easy if you have opened the file in the correct mode. You have to think about where you want to put line breaks.
f = open("myfile.txt", "w") f.write("Things to write to the file.") f.write("and a line break\n") f.close()