Opening and closing files
Opening a file
You open a file with the (surprise!) open()
built-in function.
f = open("test.txt")
You can open a file in different modes: read-only mode, write mode etc.
# Open file for reading (default). You cannot write to this file.
f = open("test.txt", "r")
# Open file for writing. It truncates (clears) the file if it exists, and creates a new file otherwise.
f = open("test.txt", "w")
# Open file for appending. This adds new content to the end of an existing file.
f = open("test.txt", "a")
# Open file for updating (read and write). Will not truncate existing files.
f = open("test.txt", "r+")
# Open file for updating (read and write). Will truncate existing files.
f = open("test.txt", "w+") # Open file for updating (read and write).
# Open binary files instead of text files. Add a 'b' to any of the above.
f = open("test.txt", "rb")
f = open("test.txt", "wb")
f = open("test.txt", "ab")
f = open("test.txt", "r+b")
f = open("test.txt", "w+b")
I have only listed the most important modes. Please check the official documentation for a complete list of modes.
There is also a keyword argument encoding
that allows you to specify the type of encoding of the file. In Python 3, this defaults to utf-8
, which is what we need most of the time.
f = open("test.txt", "r", encoding="utf-8")
f
is a file object that is used to read and modify the file.
Closing a file
Closing a file is not strictly necessary as Python will do it automatically. However, it is a good practice to actually close your files when no longer needed to free up system resources.
Files are closed with f.close()
.
Once you close the file, you will no longer be able to access your file from your program. You will have to open the file again if you want to edit further.
If you have errors while trying to close the file, the program may exit and the file will not be closed (and you may not be able to open your file)
The best practice is therefore to work with file inside a with
statement:
with open("test.txt") as f:
# do some file operations here
pass
There is no need to close your files when you use the with
keyword. Python will do it for you.