Skip to main content

Section 10.3 Opening a File

As an example, suppose we have a text file called daily_weather.txt that contains statistics about a month’s worth of weather data. The format of the data file is as follows: date, low temperature, and high temperature (in degrees Celsius).
Data: daily_weather.txt
2022-06-01,12,29
2022-06-02,13,25
2022-06-03,14,24
2022-06-04,15,24
2022-06-05,17,27
2022-06-06,14,25
2022-06-07,13,26
2022-06-08,14,26
2022-06-09,13,33
2022-06-10,17,36
2022-06-11,18,33
2022-06-12,15,27
2022-06-13,13,24
2022-06-14,14,30
2022-06-15,14,28
2022-06-16,12,23
2022-06-17,13,22
2022-06-18,11,23
2022-06-19,11,29
2022-06-20,13,31
2022-06-21,16,39
2022-06-22,21,36
2022-06-23,18,32
2022-06-24,17,31
2022-06-25,14,28
2022-06-26,15,27
2022-06-27,15,28
2022-06-28,14,28
2022-06-29,13,23
2022-06-30,14,23
Although it would be possible to consider entering this data by hand each time it is used, you can imagine that it would be time-consuming and error-prone to do this. In addition, it is likely that there could be data from other months. It is definitely advantageous to have this data in a file.
To open this file, we call the open function. This function takes two parameters: the path to the file and the mode we want for the file—either for reading data (with argument 'r') or writing data (with argument 'w'). The open function returns a reference to the file object returned by open. When we are finished with the file, we always close it by using the close method. After the file is closed any further attempts to use the file reference will result in an error.
Here is an example of opening the temperatures file for reading and then closing it right away.
fileref = open("daily_weather.txt", "r")
# file processing goes here
fileref.close()