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.
1 2 3 4 5 6 7 8 |
# 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.
1 2 3 4 5 6 7 |
# 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 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.
1 2 3 4 |
# 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.
1 2 3 4 5 6 7 8 9 10 11 |
# 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.
What do you think will happen if we try to add more content inside the test.txt
file and run the above code?
1 2 3 4 5 6 7 8 9 10 11 |
# 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.
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.
1 2 3 4 5 6 7 8 9 10 11 |
# 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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.
1 2 3 4 5 |
# 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.
The following code will show how we can write binary data into the file.
1 2 3 4 5 6 7 |
# 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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.
1 2 3 4 5 |
Traceback (most recent call last): .... read_data = file.read() io.UnsupportedOperation: not readable True |
Bonus – Pet Adoption project
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
''' A Python program to adopt a pet and appending the details in a file. The entry can also be viewed by reading the file ''' import datetime # Defining main function def get_pet(pet): # If user input 1 then this condition executes if pet == 1: adopt = int(input("Press 1 for Pet Dog 2 for Pet Cat: \n")) if adopt == 1: with open("Pet-Dog.txt", "a") as f: f.write(str(datetime.datetime.now()) + ": " + f"{name_inp} just adopted a Dog. \n") print("Successfully Entered.") elif adopt == 2: with open("Pet-Cat.txt", "a") as f: f.write(str(datetime.datetime.now()) + ": " + f"{name_inp} just adopted a Cat. \n") print("Successfully Entered.") else: print("We have only CATS and DOGS.") # If usr input 2 then this condition executes elif pet == 2: info = int(input("Enter 1 for Pet Dog Details 2 for Pet Cat Details: \n")) if info == 1: with open("Pet-Dog.txt") as f: for content in f: print(content, end='') elif info == 2: with open("Pet-Cat.txt") as f: for content in f: print(content, end='') else: print("Enter Valid Option!!") else: print("Choose 1 for adoption and 2 for Information...") if __name__ == '__main__': print("------------ Welcome to Pet Adoption Center -----------") # Username Input name_inp = input("Enter your name: \n") # Taking Input from users user_input = int(input("Press 1 for Adoption 2 for Information: \n")) # Conditions according to user input if user_input == 1: get_pet(user_input) else: get_pet(user_input) |
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ββ