How Python Handles Files?

If you are working in a large software application where they process a large number of data, then we cannot expect those data to be stored in a variable as the variables are volatile in nature. Hence when are you about to handle such situations, the role of files will come into the picture.

As files are non-volatile in nature, the data will be stored permanently in a secondary device like Hard Disk and using python we will handle these files in our applications.

Are you thinking about how python will handle files?

Let’s take an Example of how normal people will handle the files. If we want to read the data from a file or write the data into a file, then, first of all, we will open the file or will create a new file if the file does not exist and then perform the normal read/write operations, save the file and close it.

Similarly, we do the same operations in python using some in-built methods or functions.

Types Of File in Python

There are two types of files in Python and each of them is explained below in detail with examples for your easy understanding.

They are:

Binary files in Python

Most of the files that we see in our computer system are called binary files.

Example:

All binary files follow a specific format. We can open some binary files in the normal text editor but we can’t read the content present inside the file. That’s because all the binary files will be encoded in the binary format, which can be understood only by a computer or machine.

For handling such binary files we need a specific type of software to open it.

For Example, You need Microsoft word software to open .doc binary files. Likewise, you need a pdf reader software to open .pdf binary files and you need a photo editor software to read the image files and so on.

Text files in Python

Text files don’t have any specific encoding and it can be opened in a normal text editor itself.

Example:

In this tutorial, we will see how to handle both text as well as binary files with some classic examples.

Python File Handling Operations

Most importantly there are 4 types of operations that can be handled by Python on files:

Other operations include:

How to Open a File

To open a file, you need to use the built-in open function. The open function returns a file object that contains methods and attributes to perform various operations on the file.

Syntax

file_object  = open("filename", "mode")

Here,

More details of these modes are explained below

How to Create a File

With Python you can create a .text files (guru99.txt) by using the code, we have demonstrated here

Step 1)

f= open("guru99.txt","w+")

Step 2)

for i in range(10):
f.write("This is line %d\r\n" % (i+1))

Step 3)

f.close()

Here is the result after code execution

When you click on your text file in our case “guru99.txt” it will look something like this

How to Append Data to a File

You can also append/add a new text to the already existing file or a new file.

Step 1)

f=open("guru99.txt", "a+")

Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.

Step 2)

for i in range(2):
f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append mode.

You can see the output in “guru99.txt” file. The output of the code is that earlier file is appended with new data.

How to Read a File

You can read a file in Python by calling .txt file in a “read mode”(r).

Step 1) Open the file in Read mode

f=open("guru99.txt", "r")

Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

if f.mode == 'r':

Step 3) Use f.read to read file data and store it in variable content

contents =f.read()

Step 4) print contents

Here is the output

How to Read a File line by line

You can also read your .txt file line by line if your data is too big to read. readlines() code will segregate your data in easy to read mode.

When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

How to Close a File

Python file method close() closes the opened file. A closed file cannot be read or written any more. Any operation, which requires that the file be opened will raise a ValueError after the file has been closed. Calling close() more than once is allowed.

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Syntax

Following is the syntax for close() method −

fileObject.close()

Return Value

This method does not return any value.

Example

The following example shows the usage of close() method.

#!/usr/bin/python# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

When we run above program, it produces following result −

Name of the file:  foo.txt

Perform remove operation

Python list method remove() searches for the given element in the list and removes the first matching element.

Syntax

Following is the syntax for remove() method −

list.remove(obj)

Parameters

Return Value

This Python list method does not return any value but removes the given object from the list.

Example

The following example shows the usage of remove() method.

#!/usr/bin/pythonaList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print "List : ", aList
aList.remove('abc');
print "List : ", aList

When we run above program, it produces following result −

List :  [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']

File Modes in Python

Following are the various File Modes in Python:

Here is the complete code

Python 3 Example

def main():
f= open("guru99.txt","w+")
#f=open("guru99.txt","a+")
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
f.close()
#Open the file back and read the contents
#f=open("guru99.txt", "r")
#if f.mode == 'r':
# contents =f.read()
# print (contents)
#or, readlines reads the individual line into a list
#fl =f.readlines()
#for x in fl:
#print(x)
if __name__== "__main__":
main()

Summary

Thank you for your valuable time, keep learning!!

Passionate about ML