You are currently viewing File IO In Python – Opening, Reading & Writing

File IO In Python – Opening, Reading & Writing

Files are used to store information, and when we need to access the information, we open the file and read or modify it. We can use the GUI to perform these operations in our systems.

Many programming languages include methods and functions for managing, reading, and even modifying file data. Python is one of the programming languages that can handle files.

In this article, we’ll look at how to handle files, which includes the methods and operations for reading and writing files, as well as other methods for working with files in Python. We’ll also make a project to adopt a pet and save the entry in the file.

Primary operation – Opening a file

We must first open a file before we can read or write to it. Use Python’s built-in open() function to perform this operation on the file.

Here’s an example of how to use Python’s open() function.

file_obj = open('file.txt', mode='r')

We specified two parameters. The first is the file name, and the second is the mode, which determines the mode in which we want to open the file.

There are several modes to open files, and the most commonly used ones are listed below.

r – Read. The file opens in read mode. Shows an error if the file doesn’t exist.

w – Write. The file opens in write mode. Creates a file if the file doesn’t exist.

a – Append. The file opens in append mode. Writes data into an existing file.

x – Create. Creates a file. If the specified file exists, returns an error.

To specify in which mode a file should be handled, we can use

t – Text. The file opens in text mode which means the file will store text data. It is a default mode.

b – Binary. The file opens in the binary mode which means the file will store binary data.

Hence, the primary task is to open a file on which you must operate and specify the mode specific to the work you wish to perform on the file.

Reading a file

We can open the file reading mode after specifying the file name to the open() function. This is the default value; if the mode parameter is not specified, the file will open in the default read and text mode.

To perform this operation, we have a file called text_file.txt which has some content inside it.

We successfully read the content inside the file by iterating them using the Python for loop.

Using read()

We can use file.read() to read the characters from the file. Here’s a code that will read the content from the file.

Closing the file

When we’re done working with files, we need to close them so that the resources associated with them can be released. After working with a file, it is best practice to close it.

We can use file.close() to close the current working file.

The code returned True which means the file was closed successfully.

Using with keyword

Python’s open() is a context manager, so we can use with keyword with it to open and read the file’s content.

Here, open() will open the file and returns the file object and then the as keyword will bind the returned value to the file. We can now use file to print the content. Then the file will be automatically closed.

Writing into file

As we saw in the upper section, if we want to write data into the file then we need to use the 'w' mode. But before writing data into the file, remember that

  • If the specified file does not exist, a new one will be created.
  • If the specified file already exists, the data within it will be replaced with new data.

In the following code, we’ll create a new file and then write some content inside it.

The file name test.txt will be created and the content will be written inside it.

File create and data was written

What do you think will happen if we try to add more content inside the test.txt file and run the above code?

The previous content will be erased and the new content will be written.

Content replaced

Appending data to the file

We can append data to files by opening them in 'a' mode. This will not overwrite our existing content but rather add new data to the file.

The test.txt file will be opened in append mode, and the content will be appended to it without overwriting any existing data.

Data appended to the file

Using readlines()

Now that we have some content stored in two different lines in our file, it’s a good time to demonstrate the readlines() function.

The readlines() function allows us to read the content of the file line by line. Our test.txt file contains two lines so we used the readlines() function twice.

Reading & writing binary data

Binary('b') mode is available for reading and writing binary data. We must specify 'rb' to read the binary content from the file, and similarly, 'wb' to write binary data into the file.

We’ll get data as shown in the image below.

Bytes of the image

The following code will show how we can write binary data into the file.

We overrode the image file’s previous content and added new content. Now, if we read the image’s bytes, we’ll get the output shown below.

Image bytes overrode

The image file is now corrupted and we won’t be able to open this image.

Exception handling – try… finally

When we encounter errors or exceptions while performing a specific operation on a file, the program exits without closing the file. As a result, we must take precautions to address this issue.

We can use a try-finally block to handle the exception. The following code shows how to use it.

The above code will return an error stating that the read operation is not supported, but instead of terminating immediately, the program will run the block of code written within the finally block, resulting in the file being closed.

Bonus – Pet Adoption project

Here’s a simple Python program that prompts the user to select which operations they want to perform after they enter their name. When a user performs an adoption operation, the name is saved in the file along with the current timestamp. The user can view the information stored in the file by performing the information operation.

Go ahead and run it in your code editor and also try to make a better version of it.

Conclusion

With code examples, we learned the fundamental operations of creating, reading, writing, and closing files in this article. To perform these operations, the file must first be opened, and then the mode specific to the operation we want to perform on the file must be specified.

If no mode is specified, read and text mode is used to open a file, and we can also write and read binary data from the file.

We’ve also written a Python program in which a user can adopt a pet for themselves, and the data is saved in a file.


πŸ†Other articles you might be interested in if you liked this one

βœ…How to open and read multiple files simultaneously in Python.

βœ…Reading and writing zip files without extracting them in Python.

βœ…Perform high-level file operations on the file using the shutil module in Python.

βœ…Take multiple inputs from the user in a single line in Python.

βœ…enumerate() function in Python.

βœ…How to use async-await in Python.

βœ…Perform a parallel iteration over multiple iterables using zip() function in Python.


That’s all for now

Keep Coding✌✌