A Complete Guide on File Handling in Python
Have you ever wondered what the role of file handling is in Python? It is responsible for functions such as storing information or data. Using files in programming languages is equally important as in digital applications. The operation is useful when you want to store some important information. This blog gives you a thorough understanding of file handling, with descriptive examples, necessary functions, and its advantages and disadvantages.
File Handling: An Overview
The file operation comes in handy when you want to contain some important information as it works like a container. It is necessary for any working model, to have enough space to organize the data so it is easily accessible. In Python, file handling works in three ways which are:
- Opening the file
- Working on a file, that is, reading or writing
- Closing the file
Each of these steps is equally crucial and plays different roles in Python programming.
In the upcoming sections of this blog, we will discuss each of the steps involved in file handling and understand them with examples. You can also enroll in an online Python course to get a better grasp of the subject.
Why is File Handling Operation Used?
Now that we know what is file handling in Python, it is time to discuss why we prefer using it. Python has all the built-in functions that are necessary for file handling and the following are the reasons why it is used:
- It offers data persistence by allowing you to store the data beyond the run time.
- It allows easy input and output of data which makes so many operations possible.
- The files can be organized as it also offers easy-going storage and retrieval of data.
- It facilitates data processing, making analysis and cleaning of data hassle-free.
- It also provides easy sharing and communication of data.
Next up in this blog, we will talk about how to open files in Python with descriptive examples.
Opening Files in Python
This is the first step that is mandatory in file handling. You can not proceed to perform other functions like reading or writing data when you have not opened the file. The in-built open() function is used to get access to this step.
f = open(filename, mode)
Example:
# Open the file named "file.txt" in reading mode
file = open("file.txt", "r")
# Read and print each line from the file
for line in file:
print(line.strip()) # Using .strip() to remove leading/trailing whitespace
# Close the file
file.close()
In the example mentioned above, the loop prints each line that is present in the file, and the ‘r’ that is mentioned in the mode indicates that the file will open in reading mode. There are a few such modes in this function of file handling:
Mode | Function |
r | read-only mode |
w | write only mode |
a | append operation in an existing file |
r+ | read and write data mode in file |
w+ | write and read data mode in file |
a+ | append and read data in a file |
Reading Files in Python
This is the function that is used to read the file once it is opened. The in-built read() method is used to execute this function.
Example:
# Open the file named "file.txt" in reading mode using a 'with' statement
with open("file.txt", "r") as file:
# Read the entire content of the file and print it
print(file.read())
The output for the example mentioned above will be,
“This is an employee file.”
Writing Files in Python
This function is used when you are required to write something on an opened file. You can access it by ‘w’ in an open file.
Example:
with open('file.txt', 'w') as file:
file.write("Employees are important.\n")
file.write("Companies need employees to grow.\n")
The output of this example will be:
Employees are important.
Companies need employees to grow.
You have to be aware of two things when you are using this function in a file:
- A new file will be created if you try to open a file that does not exist.
- The previous content of the file will be deleted if it exists.
Closing Files in Python
This command is used in Python when you are done performing operations that you were required to in the file. The file is closed using the close() function and it makes sure to free any resources tied to the file.
Example:
# Open the file named "test.txt" in read mode
file1 = open("test.txt", "r")
try:
# Read the file content
read_content = file1.read()
print(read_content)
except FileNotFoundError:
print("File not found!")
except IOError:
print("Error reading the file!")
# Close the file
file1.close()
The file should always be closed after the operations have been executed, it is considered a good programming practice and saves up any issues that may occur in the file later.
Implementing All Functions in File Handling in Python
It is possible to implement all the functions in file handling. The following is an example:
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
print(contents)
except IOError:
print("Error: could not read file " + filename)
def append_file(filename, text):
try:
with open(filename, 'a') as f:
f.write(text)
print("Text appended to file " + filename + " successfully.")
except IOError:
print("Error: could not append to file " + filename)
def rename_file(filename, new_filename):
try:
os.rename(filename, new_filename)
print("File " + filename + " renamed to " + new_filename + " successfully.")
except IOError:
print("Error: could not rename file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Now that you know all the functions that can be used in file handling and have learned to implement them, let us move forward with the advantages and disadvantages of file handling in Python.
Advantages of File Handling
The advantages of file handling are:
- It provides versatility by allowing you to perform a variety of functions.
- It helps you work with different files hence it is flexible.
- It has a user-friendly interface.
- It is a cross-platform as it works across different platforms effortlessly.
Disadvantages of File Handling
The disadvantages of file handling are:
- The operations are error-prone.
- There is a security risk with file handling.
- If you work with advanced operations then file handling may be complex.
- The performance is slower as compared to other programs.
Conclusion
This blog talked descriptively about file handling in Python. A file works as a container to store necessary data and it is extremely helpful for all the functions that contain huge amounts of data. However, it is crucial to have a sufficient amount of knowledge of the functions before using the operations of file handling.