File Handling In Python

Before starting off with File Handling we must understand that what is a File. We usually use term “File”, but have we ever thought that why they are used?

The answer to this question is: For persistent data. To store data we use them, but in case we want data to be stored forever, even if the application is closed then files come into the role. These files can be anything, a plain text file with .txt extension, or it could be a binary file like an image with .jpg extension, or it could be a spreadsheet or excel file.

A sample text file is like,

In this above example, we have created a simple notepad file and named it as sample.txt

Now you must be wondering that how we can embed or do file operations within Python! Let’s get started and see how we can open a file within python.

OPENING A FILE

To open a file, we use method open (), it has various parameters but 2 main parameters are:

  1. Filename – This is a mandatory parameter, this would be the name of the file that you want to open, in some IDE you can just mention the filename but in others, you need to mention the extension also, like- .txt, .jpg etc.
  2. Access Mode – This is an optional parameter, this means that in which mode you want to open the file like- read, write, binary, etc. But even if you don’t mention this parameter, the default value is ‘r’ i.e. read mode.

SYNTAX

open(‘filename’,’mode’)

Example

open('sample.txt','r')

Output

You won’t see any output on the console, the file will be compiled and will run because the file has been opened in the backend.

READING A FILE

To read a file, we need to open a file in read mode. That means the access mode should be ‘r’. Now, we will learn about read() method.

read() method is used to read a file and when used with print statement it will print all the data inside that file. For example-

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.read())

Output

Example 2

When you want to display only the first line of the data inside a file.

We use method readline() in this case, let’s see how it’s used:

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readline())

Output

If you use this method twice, so it will print the next line also, but along with a new line, like,

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readline())
print(variableToStoreFile.readline())

Output

If you don’t want this new line space or gap between the line then we use, a parameter ‘end’ inside readline() method, like

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readline(), end=โ€ โ€œ)
print(variableToStoreFile.readline())

Output

Example 3

When you want to print data by characters.

If you want to print only few characters from the file then we use method readline() but along with a parameter. Let's say you want to print only first 15 characters inside sample file, then we write:

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readline(15))

Output

For above example, read() method will also works the same as realine(), you can try,

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.read(15))

Example 4

When you want the data in the form of a list.

All the data inside your file will be printed in the form of list if we use method readlines(). So our sample file have 3 lines inside it, using readlines() method, will give us output as a list with 3 components in it, like-

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readlines())

Output

The parameter inside readlines() method doesn’t work, it will give you a blank list like,

variableToStoreFile= open('sample.txt','r')
print(variableToStoreFile.readlines(2))

Output

WRITING IN A FILE

To write in a file, we need to open a file in write mode first. That means, the access mode should be ‘w’. Now, we will learn about write() method.

open('sample.txt','w')

This statement will simply open the sample file in the backend. But what if we write:

open('test.txt','w')

This file ‘test’ is not existing, we haven’t created any file like test in our directory. Now how will python open this in backend if it is not existing?

The beauty of python is that when you open a file in write mode i.e.’w’ and that file is not existing, it will create one with the same name. This would be a blank file though. Now, to write something in this file, we will use write() method:

variableToStoreFile= open('test.txt','w')
variableToStoreFile.write("Writing something in file")

But this will give no output on the console and even will not update any data in the file. So, after writing we also have to read the file in order to see the output and insert written data in the file.

variableToStoreFile= open('test.txt','w')
variableToStoreFile.write("Writing something in file")
variableToStoreFile.close()
file_variable= open('test.txt','r')
print(file_variable.read())

Console Output

File Output

In the above example, we also closed the file using close() method, similar to open() method, close() method is used to close the file in the backend. We need to close the file because after closing it we cannot perform any read or write operation on it. Though python automatically closes the file so we don’t need to use this method but it is a good practice to do so.

Now after writing this if I try to write in this file again, like

variableToStoreFile= open('test.txt','w')
variableToStoreFile.write("Something More")
variableToStoreFile.close()
file_variable= open('test.txt','r')
print(file_variable.read())

OUTPUT

This is overwriting the content in the file, meaning: It will remove the previous data and write this new one.

APPENDING IN A FILE

If you don’t want previous data to be removed and want to insert data after the existing data inside a file, then we use ‘a’ i.e. append mode.

We open the file in ‘a’ mode and then using write() method we can achieve the same. Like-

variableToStoreFile= open('test.txt','a')
variableToStoreFile.write("Appended data")
variableToStoreFile.close()
file_variable= open('test.txt','r')
print(file_variable.read())

Console Output

File Output

Practice Questions

Question 1 - Write a program to read data from file1 and write the same data in file2.

Files before implementation,

fileToReadData= open('sample.txt','r')
fileToWriteData= open('test.txt','w')
for i in fileToReadData:
 fileToWriteData.write(i)
fileToReadData.close()
fileToWriteData.close()
fileToWriteData= open('test.txt','r')
print(fileToWriteData.read())

Console Output

File Output

Question 2 - Write a program to read a file with an image inside it and then display it in a file.

Note- Images are binary files, so use ‘b’ as binary as the access mode to read and write files with images.

fileToReadImage= open('broklyn.jpg','rb')
fileToWriteImage= open('test.jpg','wb')
for i in fileToReadImage:
 fileToWriteImage.write(i)
fileToReadImage.close()
fileToWriteImage.close()
fileToDisplayData= open('test.jpg','rb')
print(fileToDisplayData.read())

There would be no output on the console but there would be a new file created with name ‘test’ and extension as .jpg in the particular directory and then you would be able to see it as a picture in binary format.

Here, broklyn.jpg was original file that we read and test.jpg is new file that was created when we opened this file in write mode, like

And when we try to open test.jpg, it looks like,

File Handling in Python

Try it!

Summary

In this article we learned about all the basic operations of file handling, you now know that how to handle files in python, how to open a file, read it, write or append in a file and close a file. And we also learned operations with the help of examples.

In my next article, we will learn about CSV in python using File handling.

Thanks for reading!


Recommended Free Ebook
Similar Articles