Now that you have seen and practiced a bit with opening and closing files, there is another mechanism that Python provides for us that cleans up the often forgotten close
. Forgetting to close a file does not necessarily cause a runtime error in the kinds of programs you typically write in an introductory CS course. It will rarely, if ever, cause a problem if you forget to close an input file. However, if you forget to close an output file, there is a possibility that some of your data will not get written to the file.
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