The most recommended way to close a file in Python is to use the with statement, which uses a context manager. It automatically closes the file when the “with statement” block is complete, without requiring an explicit close. It is an advantage over the close() method.
Reading a file
Let’s read a data.csv file. For opening a file, we will use the “with open()” statement, and then we will read its content using the file.read() method.
with open('data.csv', 'r') as file:
content = file.read()
print(content)
# Output:
# stocks,price
# Kaynes,5638
# V2Retail,1956
The data.csv file looks like this:
Writing a file
You can also use the “with statement” to write content to a file. Once the block is complete, it will automatically close and free the resources.
with open('data.txt', 'w') as file:
file.write('Netweb Tech!')
Handling multiple files
Starting with Python 3.1, you can manage multiple context managers in a single with line, separated by commas. Let’s copy the content of the data.txt file to the info.txt file using multiple context managers.
with open('data.txt', 'r') as infile, open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line.upper())
So, whatever the content is in the data.txt file, we will copy it to another output.txt file with all text in uppercase.
Alternate approach: Using the close() method
The close() method is not the best way, but it will do the job of closing a file if you have opened it using the open() method. It’s straightforward but requires manual handling, especially in error-prone code.
Reading a file
Let’s open the data.txt file using the open() function, read the file using the read() method, and close the file using the close() method.
file = open('data.txt', 'r')
content = file.read()
file.close()
print(content)
# Output: Netweb Tech!
Here, the only disadvantage is that you need to close the file manually to free up the resources.
After close(), the file object is no longer usable for I/O operations.
Writing to a file
For the writing operation, you also open the file, write it, and close the file. Without a close() method, writings might not be saved if the program exits immediately.
file = open('app.txt', 'w')
file.write('Hello, World!')
file.close()
That’s all!




