File Handling in Python

Sneak Peek! Master File Handling in Python | 10 mins read

Table of Contents

85 / 100

Table of Contents

Introduction

Good to Go

Holla, Welcome back to another exciting tutorial on “File Handling in Python ”. In this Python tutorial, you’ll learn how to perform read and write operations on a file ,open() and close() functions and various other operations.

If you aren’t following along, I would recommend you to go back where you left or start from here.

File handling is the most important feature of a programming language. It consists of retrieving and storing the data from a file using a program.
Basic functionalities that we will be learning in this tutorial are:-
  • Creating a new file
  • Opening an existing file
    • Several modes in which a file can be opened
  • Reading the data from the file
  • Writing the data on the file
  • Closing the file

File handling in python is based on open() function.

The open() function

The beginning

The first step in file handling in python is to open the file using open() function. It takes file path file as first required argument and return the file object.
HEADER OF OPEN FUNCTION
Parameters in open function

All the argument values in the header are default values.

Let us understand what is the meaning of each parameter.

  • file – This parameter is required and takes location(path) of the file as argument.
  • mode – It takes string as argument.A file can be open in various modes like read,write,update,binary mode etc. We will look into this in detail in further sections.
  • buffering – It takes integer value as argument.The value can be:-
    • 0 – buffering off
    • 1 – line buffering
    • -1
      • For binary files,fixed size buffer is used such as 4096 or 8192 bytes.
      • For text files, line buffering.
    • >1 – Set the size of buffer in bytes
  • encoding – It defines how a file is encoded or decoded. ASCII and utf_8 are some standard encodings.The default encoding depends on the platform.
  • errors – It takes string as argument that defines how encoding and decoding errors will be handled.For instance,
    • ‘strict’ or None – to raise ValueError exception.
    • ‘ignore’ – to ignore errors.
  • newline – This takes string as argument to determine the end of a line . For instance,’ ‘,’\n’,’\r’, etc.
  • closefd – It takes boolean value as argument
    • True – default value when filename is given to file parameter.
    • False – When file descriptor(A number that identify a open file in a OS)
  • opener – It takes a callable function which return the value of open file descriptor.The default value is None.

The close() method

An opened file needs to be closed else the file remains in the main memory and affects the performance.To close a file,we use close method.

SYNTAX:- fileobject.close()

  • It doesn’t return any value.
  • It destroys the fileobject and any further operation using that fileobject leads to error.
  • close method can be called multiple times.

For example,

Let say we have text file named topictrick.txt . When we open this file, it returns a file object.We read the content of file using read method(discussed in further sections) and then close the file.

We uses close function twice and do not get any error. But a ValueError exception is raised when we try to read the file after it is closed.

>>> file = open('topictrick.txt','r')
>>> file.read()
'Hi! This is your tutor, Harry.\n'
>>> file.close()
>>> file.close()
>>> 
>>> #This will give error
>>> file.read()
Traceback (most recent call last):
File "", line 1, in 
ValueError: I/O operation on closed file.
>>> 

Opening file in different modes

Choose according to need

Mode Meaning file exists file not exists
r
Default Mode ,Opens the file for reading only
The file pointer is at start of the file
File Not Found Error
r+
Opens the file for reading and writing
The file pointer is at start of the file
File Not Found Error
w
Opens for writing only
Overwrites the file
Create a new file
w+
Opens the file for writing and reading
Overwrites the file
Create a new file
rb
Opens the file for reading in binary format
The file pointer is at start of the file
File Not found Error
rb+
Opens the file for reading and writing in binary format
The file pointer is at start of the file
File Not found Error
wb+
Opens the file for reading and writing in binary format
Overwrites the file
Creates a new file
a
Opens a file for appending
The file pointer is at end of file
Creates a new file
a+
Opens the file for appending and reading
The file pointer is at end of the file
Creates a new file
ab
Opens the file for appending in binary format
The file pointer is at end of file
Creates a new file
ab+
Opens the file for appending and reading in binary format
The file pointer is at end of the file
Creates a new file
x
For python3 and above, Used to avoid accidental overwrites of existing file as in case of 'w' and 'a' mode
File Exists Error
Creates a new file and opens it in writing mode
x+
For python3 and above, Used to avoid accidental overwrites of existing file as in case of 'w' and 'a' mode
File Exists Error
Creates a new file and opens it in writing and reading mode

Pythonic way of opening and closing a file

Read or Write

WHY?

Closing a file manually using close() function is a tedious task .Specially ,when you are working with thousands of files . It is possible that you may forget to close some of them which in long run cause resource leakage and system crash.

Let us see an example to know how this happen:-

>>> file_obj = []
>>> for i in range(100000):
...     file_obj.append(open('temp.txt','w'))
... 
Traceback (most recent call last):
File "", line 2, in 
OSError: [Errno 24] Too many open files: 'temp.txt'
>>> 

In the example, We loop 100000 times and call open() function to open a file name temp.txt in write mode .We are not closing any of the file .Hence , got the error.

HOW?

Let us understand with an example:-

>>> with open('topictrick.txt','r') as myFile:
...     print(myFile.readline())
... 
I AM OPENED USING WITH KEYWORD.HENCE NO NEED TO CLOSE ME!!.
>>> 
>>> # Now if I use myFile object to print the content of file it will give an erro
>>> print(myFile.readline())
Traceback (most recent call last):
File "", line 1, in 
ValueError: I/O operation on closed file.
>>> 

In the example,

  • open() function is same as we discussed above.
  • myFile is the alias we used to access the file object returned by open function
  • All the operations on file is handled within the block
  • When the execution of program exit the block the file is automatically closed.
    • PROOF
      • When we try to print the content of file outside the block it shows the error that the file is closed.

Conclusion

Now , you are familiar with open function , close method and different modes to open a file. The efficient way to open a file using with keyword. I advised you to work on some mini projects and gets hands on experience with file handling in python.

Last but not the least, do leave your feedback and suggestions. We would love to hear your feedback.

Till then , keep coding