Opening and Closing Files in Python
To work with files, you first need to open them. In Python, the open
function is used to open files.
The open
function has several parameters, which are described in the “Built-in Functions” article. For now, three parameters are important for us:
- The first parameter is the file name. The file path can be relative or absolute.
f = open('text.txt', 'r')
- The second parameter is the mode in which we want to open the file.
Mode | Description |
---|---|
‘r’ | Open for reading (default value). |
‘w’ | Open for writing, contents of the file will be deleted. If the file does not exist, a new file will be created. |
‘x’ | Open for writing, but only if the file does not exist. An exception is raised if the file exists. |
‘a’ | Open for appending, data is added at the end of the file. |
‘b’ | Open in binary mode. |
‘t’ | Open in text mode (default value). |
‘+’ | Open for both reading and writing. |
The modes can be combined, such as ‘rb’ meaning reading in binary mode. The default mode is ‘rt’.
- The final parameter,
encoding
, is used only when reading files in text mode. This parameter sets the encoding.
Once we have opened the file, we will want to read data from it. There are several ways to do this, but the two most interesting ones are:
- Using the
read
method, which reads the entire file if called without arguments, and readsn
characters if called with an integer argumentn
.
# Reading from files
print(f.read(1)) # 'H'
print(f.read()) # 'ello world!\nThe end.\n\n'
- Using a
for
loop to read the file line by line:
for line in f:
print(line)
Writing to Files
Now let’s consider writing to files. Let’s try to write the following list to a file:
l = [str(i) + str(i - 1) for i in range(20)]
f = open('text.txt', 'w')
for index in l:
f.write(index + '\n')
f.close()
For those who do not understand what these numbers are: the write
method returns the number of characters written.
After working with a file, it is necessary to close it using the close
method.
f.close()
Now let’s try to reconstruct this list from the resulting file. We will open the file for reading (I hope you understand how to do this by now) and read the lines.
f = open('text.txt', 'r')
l = [line.strip() for line in f]
f.close()
We get the same list that we initially created. For more complex cases (like dictionaries, nested tuples, etc.), designing the writing algorithm is more difficult. However, there is no need to worry about this either. Python already has tools like pickle
or json
for handling complex data serialization and deserialization.