File Handling in Python

Riya Jain
6 min readJan 2, 2021

Python has been widely used in almost all the domains today and shows no sign of slowing down. This is because of all the features that Python provides to the developers. And, file handling is one of its top features.

Why Do You Need File Handling

File handling has always been a huge part of the development community. But, why?

Take a minute and think about this situation — You have a server running and you need to access files present on that server. You can do this locally by giving some input to your python program on the server. So, what are the ways to input something to Python?

  • Standard input
  • Command-line arguments

But, what if you had to read lots and lots of data which is not practical to type in every single time. It doesn’t make sense to type it out all the time.

So, what is the easiest way out here to store whatever input you want in one place and keep using it as long as your requirement is met? The answer is? Files!

Types Of Files Supported

Can you quickly think of all of the types of files that you know? Image, audio, video, text, scripts, and many more. The dependency on the OS is the most important thing to keep in mind when considering the type of files supported.

Windows supports all of the file types mentioned above. But does it support every type of file? Absolutely not! There are certain limitations here as well.

Now, coming to Python — There are 2 types of files: Binary and Text.

Text files are structured as a sequence of lines, where each line includes a sequence of characters. This is what you know as code or syntax. Each line is terminated with a special character, called the EOL or End of Line character.

A binary file is any type of file that is not a text file. Because of their nature, binary files can only be processed by an application that knows or understand the file’s structure. They are categorized as the generic 0’s and 1’s in Python.

File Operations

What are the various file operations that you can generally perform? I call it CRUD which stands for: Create, Read, Update, Delete

However, do note that there are many other operations that can be performed with the files as well. Such as, copying a file or changing the properties of the file and filter.

Check the above flow diagram to get a quick picture of what needs to be done. First, we create a file and later open that file. We work on that file — either read or write or anything for that matter. And lastly, we close the file when are doing using it.

Coming to Python now — Creation of file can be done manually or through Python. For now, let us consider that we will do it manually by going to the location and creating a file like a text file.

Opening Files

Before we begin reading or writing, the first step is actually opening the file.

To do this, we’ll use the open() function which creates a file pointer. Our pointer will be stored in a variable. We need to specify in which way we are planning on interacting with the file. There are different modes to interact with a file, which I will tell in the next section.

So let’s take a look at some sample code:

filename = "tutorial.txt"
with open(filename, "r") as f:
print(f)
#<_io.TextIOWrapper name='tutorial.txt' mode='r' encoding='UTF-8'>

First, we assign our file’s name to a variable called filename. Then we use the with keyword with the open() function to create a read file-pointer which is referred to as f within the code block.

Notice how printing f does not print out the file, but rather the pointer’s information.

The purpose of using with is to bypass managing the file pointer. There’s nothing wrong with calling open() by itself, but then you should close the pointer once you are done with the file.

f = open("app.py", "r")
print(f)
f.close()

Using with, the pointer is automatically closed at the end of the block, saving you work.

Open Modes

These are the various modes available to open a file. We can open in read, write, append, and create mode as well. Pretty straightforward. But do note that the default mode is the read mode.

Including a mode argument is optional because a default value of ‘r’ will be assumed if it is omitted. The ‘r’ value stands for read mode, which is just one of many.

The modes are:

r’ — Read mode which is used when the file is only being read
w’ — Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated)
a’ — Appending mode, which is used to add new data to the end of the file; that is new information is automatically amended to the end
r+’ — Special read and write mode, which is used to handle both actions when working with a file

Note that you can open a file in read mode only if it exists as well. If you try to read something that doesn’t exist then Python will greet you with a beautiful error message.

In addition, you can specify if the file should be handled as binary or text mode along with the mode as well. You can have the mode as wt so it means that the file is to be opened in the write mode and the file Python is opening is a text file.

Example

f = open(“example”,”w”)  
print f

This snippet opens the file named “example” in writing mode so that we can make changes to it. The current information stored within the file is also displayed.

Once this has been done, you can move on to call the objects functions. The two most common functions are read and write.

Reading Files

There are three methods to choose from when reading a file.

  1. read() will return the entire file or up to the number of bytes if specified
  2. readline() will return a single line or up to the number of bytes if specified
  3. readlines() will return the entire file or up to the number of bytes if specified, split into a list of lines

If you’re planning on running a single command like a print, then read() is generally sufficient; however, if you plan to work with the read data then I recommend readlines() which helps break apart the file.

with open("practice.txt", "r") as f:
print(f.read()) # will print the entire file
lines = f.readlines()
for line in lines:
print(line) # will print one line at a time

Writing Files

Unlike reading files, there are two modes available when you want to write to a file. If your goal is to write as if new, then use write (w) mode. This will erase any existing content in your file. If you want to preserve the current contents, then use append (a) mode and your new content will be written to the end of the file.

There are two write methods: write and writelines. Use write() for a single string and writelines() for a list of strings — similar to how readlines() returns a list of lines.

one_line = "Hello World"
multiple_lines = ["Hello World","Nice to Meet You"]
with open("practice.txt", "w") as f:
f.write(one_line)
f.writelines(multiple_lines)

Closing A File

When you’re done working, you can use the f.close() command to end things. What this does is close the file completely, terminating resources in use, in turn freeing them up for the system to deploy elsewhere.

It’s important to understand that when you use the f.close() method, any further attempts to use the file object will fail.

That’s all for this blog. Thanks for reading.

--

--

Riya Jain

I am a B.Tech. Undergrad and loves programming. Scholar at Google Women Techmakers and currently exploring different tech fields.