Opening, Reading & Writing Files In Python

Sachin Pal
7 min readMar 21, 2023

--

File handling in Python
Source: Author(GeekPython)

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.

# Using open() function
file = open('text_file.txt', 'r')
# Printing the content inside the file
for content in file:
print(content)

----------
Hey, there Geeks. Welcome to GeekPython.

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.

# Using open() function
file = open('text_file.txt', 'r')
# Reading file using read()
print(file.read())

----------
Hey, there Geeks. Welcome to GeekPython.

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.

# Using open() function
file = open('text_file.txt', 'r')
# Reading file using read()
print(file.read())

# Closing the file
file.close()
# Checking if the file is closed or not
print(file.closed)

----------
Hey, there Geeks. Welcome to GeekPython.
True

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.

# Using with keyword
with open('text_file.txt', 'r') as file:
# Printing the content
print(file.read())

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.

# Creating and writing in a file
with open('test.txt', 'w') as file:
# Writing data inside the file
file.write('You guys are awesome, Thanks for reading.')
print('Data written successfully.')

# Closing the file
file.close()

----------
Data written successfully.

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

File created and data were written
File created and data were written

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

# Writing in a file
with open('test.txt', 'w') as file:
# Writing data inside the file
file.write('If you love this, Bookmark it and share this.')
print('Data written successfully.')

# Closing the file
file.close()

----------
Data written successfully.

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

Content replaced
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.

# Adding new data to the file
with open('test.txt', 'a') as file:
# Writing new data
file.write('\nPlease check other articles on GeekPython.')
print('Data written successfully.')

# Closing the file
file.close()

----------
Data written successfully.

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
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.

with open('test.txt', 'r') as file:
# Reading first line
print(file.readline())
# Reading second line
print(file.readline())

# Closing the file
file.close()

----------
If you love this, Bookmark it and share this.

Please check other articles on GeekPython.

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.

# Opening an image file in read binary mode
with open('writing.png', 'rb') as f:
# Reading the bytes of the image
print(f.read())
f.close()

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

Bytes of the image
Bytes of the image

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

# Opening image in write binary mode
with open('writing.png', 'wb') as binary_file:
# Overriding the bytes of the image
binary_file.write(b'Hello there')

# Closing the file
binary_file.close()

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
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.

try:
file = open('test.txt', 'w')
# Writing content
write_data = file.write("Hey, how it's going.")
# Trying to read the content
read_data = file.read()
print(read_data)
finally:
# Closing the file
file.close()
# Printing if file is closed
print(file.closed)

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.

Traceback (most recent call last):
....
read_data = file.read()
io.UnsupportedOperation: not readable
True

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.

That’s all for now

Keep Coding✌✌

--

--

Sachin Pal
Sachin Pal

Written by Sachin Pal

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.

No responses yet