Python gives us file handling methods within its standard library. This is really convenient as a developer since you do not really need to import any more modules for handling files.
The key methods provided to us by the Python for file handling are
Let’s go over the
open() method that allows us to open files in Python in different modes.
Open Files in Python
To open a file, all we need is the directory path that the file is located in. If it’s located in the same directory then including just the complete filename will suffice.
I’ve created a file with some sample text in it which we’ll use as a sample to learn the open file method.
1. Opening a file using the open() method
To open the OpenFile.txt and read the text contents of the file, let’s use the
open() and the
file = open('OpenFile.txt') print(file.read()) file.close()
read() method will read the entire contents of the file.
By default, the
open() method opens a file in read-only mode. To write to a file, we will need to specify that the file has to be opened in write mode.
2. Different Modes For open() Method
Let’s try to write to the file with the default mode on.
file = open('OpenFile.txt') print(file.read()) file.write("testing write") file.close()
We’ll keep the read operation as it is so we can see where the code stops.
So what are modes, and how do we add them? Below is a list of modes when using the open() method.
- r: Read-Only mode.
- r+: Read and write mode. Will not create a new file and open will fail if the file does not exist
- rb: Read-only binary mode to read images, videos, etc.
- w: Write-only mode. Overwrites existing file content. This will create a new file if the specified filename does not exist.
- w+: Read and write mode.
- wb: Binary write-only mode for writing to media files.
- wb+: Binary read and write mode.
- a: Append mode. Does not overwrite existing content
- a+: Append and read mode. It will create a new file if the filename does not exist.
- ab: Append binary mode for images, videos, etc.
- ab+: Append and read binary mode.
3. Opening Files in Write Mode in Python
There are multiple ways you can open a file in write mode in Python. Depending on how you want the file handling methods to write to a file, you can use one of the below modes.
file = open('OpenFile.txt', 'w') print(file.read()) file.close()
By adding the ‘w’ while opening the file in the first line, we specify that the file should be opened in write mode. But this operation would fail too because the file is write-only and won’t allow us to use the read() method.
file = open('OpenFile.txt', 'w') file.write('New content\n') file.close()
The above code will completely clear all the contents of the text file and instead just say “New content”.
If you do not want to overwrite the file, you can use the a+ or r+ modes.
The r+ mode will write any content passed to the
file = open('OpenFile.txt', 'r+') print(file.read()) file.write('r+ method, adds a line\n') file.close()
The a or a+ mode will perform the same action as the r+ mode with one main difference.
In the case of the r+ method, a new file will not be created if the filename specified does not exist. But with a+ mode, a new file will be created if the specified file is not available.
4. Opening Files Using the with clause
When reading files with the
open() method, you always need to make sure that the
close() method is called to avoid memory leaks. As a developer, you could miss out on adding the
close() method causing your program to leak file memory due to the file being open.
With smaller files, there isn’t a very noticeable effect on the system resources but it would show up when working with larger files.
with open('OpenFile.txt', 'r+') as file: print(file.read())
In the above example, the output would be the same as the ones we saw in the beginning, but we don’t have to close the file.
with block acquires a lock as soon as it’s executed and releases the lock once the block ends.
You can also run other methods on the data while staying within the
with code block. I’ve edited the OpenFile.txt, in this case, and added some more text for better understanding.
with open('OpenFile.txt', 'r+') as file: lines = file.readlines() for line in lines: print(line.split())
with statement does the memory handling for us as long as we continue to work within its scope. This is yet another but the better way to work with files in Python.
You should now have a grasp on how to open a file in Python and handle the different modes for opening a file with the open() method. We’ll cover further file handling methods in upcoming tutorials.