Files

0. Learning objectives


1. Files

This is the way Wikipedia defines a file: "A computer file is a computer resource for recording data in a computer storage device, primarily identified by its file name. Just as words can be written to paper, so can data be written to a computer file."

Whether we are reading or writing a file, we need a way to open files. This is done with a built-in function in Python, called the open function. The open function takes in two parameters (both are strings):

For example, to read a file called 'lyrics.txt' you would use open('lyrics.txt', 'r'). To write a file called 'frequency.txt', you would use open('frequency.txt', 'w').

Now, what does the open function returns to us? It returns a File object, specifically a _io.TextWrapper object (a built-in type). Don't worry too much about this: just think of it as a file object to iterate on. We need this file object to either read from, or write to the file depending on how we opened it.

A file object is iterable, just like strings, lists, dictionaries and range's are iterable. Remember, in the case of strings, the iteration variable iterates over characters; with lists, the iteration variable iterates over items; with dictionaries, the iteration variable iterates over the keys; with range the iterable variable iterates over the numbers generated by range. With a file object, the iteration variable iterates over the lines in the file. So typing for L in file: will iterate through all lines in file. On each iteration, L receives the next line in the file as a string.

Have a look at the example below in which:

.

When you're done with your file, you should always close it!

This can be done with the command file.close() (assuming file is the the name of the variable you used to store the file object you received from the open function).

To write contents to a file, we can use the write() function defined for file objects. This is very similar to the print() function we have been using to print information to the console. However, there are a few differences. First, we can only pass one parameter (a string) to the write function (in contrast to how you can pass in multiple things to print() separated by commas). This means you will need to create a single string (via concatenation) to write a line to a file. Second, whereas print() implicitly creates a new line after printing, you need to specify that you want a new line when using write(). Remember the '\n' (newline) characters? You can use these to create a new line in the file you are writing to.