Working with files
Often during the execution of a program it is necessary to use files for both reading and writing data. These data could be values to be read and then processed. Finally, the results of our processing often instead of displaying them on the terminal, it is much more useful to save them in a file.
So file management, both reading and writing is a very important task in Python programming. Let’s see how to perform the most common operations.
Opening a file
Text files are the easiest to use. However, before you can read or write data in a file, it must be open. This is possible in Python using the open () function.
In the line above we have written only in the file name, but in reality this is only valid if the file is in the current Python directory. In fact, the argument of open () is not the name of the file, but the path always referred to the working directory.
In fact, you often specify a second argument in the open () function that specifies how to use the file. This is defined by adding one or more characters in sequence.
- w – in writing (wrtiting)
- r – reading (reading)
- a – in append (add at the bottom of the program)
- b – binary file
For example if you want to open a file in read only and text
Note: r is the default mode, so it can also be omitted
or if you want to open a binary file in writing, we have to specify
Closing a file
Another operation, often forgotten, is to close a file once the operation we wanted to do on it is finished. To close a file, use the close() method (because it belongs to the file object)