Python is a general-purpose programming language. Here the term ‘general-purpose’ implies that it can be used for the development of various useful applications. To illustrate, building websites (the backend of Facebook runs on Python), building digital games, building applications for the phone and web browser, and applying machine learning techniques for training models and training CNNs (convolutional neural networks) in order to gain valuable insights.
In this blog, we would be concentrating on the ‘File Handling’ aspect of Python. It is very much important in today’s agentic AI paradigm since the Python code literally ‘crawls’ through your computer and can access all your files locally. As its name suggests, file handling involves handling all your files using Python code. For example, finding your file, reading content from the files, managing your files in a desired format, opening and closing your files as and when required, and so forth.
Why is file handling important in the real world?
Those programs that are being used worldwide require storing data not just during the execution of the program. Some examples include storing information about customers, employees, logs, and reports. Programs that involve reading, writing, modifying, and storing files are called file handling programs.
What is file handling in Python?
I will give you a context question for the real world. Suppose you are developing a small application for managing employees in your organization. You enter the name, id, and department of the employee, and everything goes well when you run the program. What will happen if you shut down the application? All your data that was entered may be lost if you have not saved it anywhere (in the Cloud, or in servers on-premise).
Python offers an in-built "open()" method to deal with files. Whenever we use any file, we have three main operations to do as follows:
1. Open: Open the file in the particular mode.
2. Operation: We can read the existing information or write some new information.
3. Close: We can finally close the file after completing the operation.
These operations are used as a base for file handling, and they are very helpful when we handle text files, application logs, reports, and datasets.
The next step is learning about the different File Modes in Python. Whenever we open a file in Python, we need to tell Python what we would like to do with that file. Are we going to read from that file,
The second argument passed to the "open()" function is known as the mode, which specifies how the file is going to be opened.
Here are some of the frequently used file modes:
Modes| Explanation
"r"| It opens the file for reading only. In case the file does not exist, then an exception occurs.
"w"| It opens the file for writing only. If the file does not exist, then it creates a new file.
"a"| It opens the file in append mode.
"x"| It creates a new file, if it does not exist, else it raises an error.
"r+"| It opens the existing file in read and write mode.
"b"| It opens the file in binary mode.
"t"| It opens the file in text mode. It is the default mode.
In case we need to open a file of employee records for reading purpose, then we may use:
file = open("employees.txt", "r")
In case we have to write new content to the file, then we may use:
file = open("employees.txt", "w")
One thing to note here is that "w" and "a" modes work differently. If you open an already existing file with "w" mode, the content of the file will be erased, while the "a" mode will keep the existing data but add new data to it. The right choice of the mode to open your file is crucial, as an incorrect one will lead to loss of information. Let's look at how Python reads the information in the next section.
After opening a file with the required information, we need to get and process the information in Python. There are several ways to do that depending on the amount of information and the way we would like to process it.
Let's imagine that we have an "employees.txt" file with the following records:
101, Aditi, Data Analyst
102, Rahul, Python Developer
103, Sneha, Business Analyst
104, Karan, Data Engineer
Now let us look at how we can read this file in various ways.
1. Using read()
When we need to read an entire file and get its content in a single string, then we use the "read()" method.
with open("employees.txt", "r") as file:
content = file.read()
print(content)
Output:
101, Aditi, Data Analyst
102, Rahul, Python Developer
103, Sneha, Business Analyst
104, Karan, Data Engineer
We can also decide the number of characters that need to be read. For instance, using the command "file.read(10)" would allow us to read the first 10 characters of the file.
It comes in handy when dealing with small files and requiring all data to be accessed at once.
2. Using readline()
But what if we don’t require the whole file but only require the lines one by one? Here is when "readline()" becomes important.
with open("employees.txt","r") as file:
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)
Output:
101, Aditi, Data Analyst
102, Rahul, Python Developer
Each time "readline()" is called, Python reads the next line from the file. This makes it useful when we want to process records individually rather than retrieving everything at once.
3. Using readlines()
Unlike "readline()", which retrieves one line at a time, "readlines()" retrieves all the lines and stores them in a Python list.
with open("employees.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
[
'101, Aditi, Data Analyst\n',
'102, Rahul, Python Developer\n',
'103, Sneha, Business Analyst\n',
'104, Karan, Data Engineer'
]
Observe that each line becomes an individual entry in the list. The "\n" stands for the new line character, which marks the start of one line and end of the previous one. This is helpful because when we wish to store these lines in a list and do further processing with them.
4. Reading from a File Using for Loop
One more method to read data from a file is using a "for" loop, where the entire content of the file is not loaded into the memory all at once.
with open("employees.txt", "r") as file:
for line in file:
print(line.strip())
Output:
101, Aditi, Data Analyst
102, Rahul, Python Developer
103, Sneha, Business Analyst
104, Karan, Data Engineer
In this case, “for” loop iterates over each line of the file. Here we have also used the “strip()” function in order to remove any white space before and after each line. This approach is quite efficient while dealing with large files because it does not need to load the entire file into the memory.
Writing and Appending to Files in Python
File Reading allows us to read the data in the file, but if we want to write the data or update the existing file then we make use of the “write()” and “writelines()” functions in Python.
With the help of “write()” function, we can write a string in the file.
For instance:
with open("employees.txt", "w") as file:
file.write("105, Meera, Data Scientist")
It is also imperative to observe that the “w” mode while opening the file will overwrite all the existing data inside the file. In cases where one does not want to delete the existing data, we use “a” mode.
with open("employees.txt", "a") as file:
file.write("\n106, Arjun, SQL Developer")
Another function in Python is the “writelines()” which we may need in case we wish to write several strings to a file.
employees = [
"107, Priya, HR Analyst\n",
"108, Vikram, Software Engineer\n"
]
with open("employees.txt", "a") as file:
file.writelines(employees)
It should be noted that the "writelines()" function will not add new lines, and we have to use "\n" ourselves.
File handling is an important part of the Python programming process, as this allows for storing and accessing data that exceeds the lifetime of one execution of the program. From keeping track of employees' details to logging of applications and other tasks that require data analysis, reading and writing data into/from files becomes crucial knowledge when working with Python code. File modes and such functions as "read()", "write()", and "append()" are very important in this case.
Author: Akkshhey Agarwaal,
Related Links:
Mastering Python Dictionaries.
Python and SQL Interview Questions.
Do visit our channel: SevenMentor.
Akkshhey Agarwaal
Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.