File Handling In Python

What is File Handling ?

Till now We are taking input from console and interacting with console only . But sometimes data is too large to be shown on console.The data to be displayed may be very large, and only a limited amount of data can be displayed on the console since the memory is volatile.

The file handling plays an important role when the data needs to be stored permanently into the file. A file is a named location on disk to store related information. We can access the stored information (non-volatile) after the program termination.

The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in Python.

Hence, a file operation can be done in the following order:

1.Open a file with access mode 2.Read or write - Performing operation 3.Close the file

Opening a file :

To perform any operation in file , we must need to open the file.

Files must be opened with an access mode.

Access mode means how do you want to access a particular file.

Types of Access modes :

x - it is used to create a new file with specified name. It throws error if file name exists already.

r - It opens the file to read-only mode.The file is by default open in this mode if no access mode is passed.

w - It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name.

a - It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.

r+ - It opens the file to read and write both. The file pointer exists at the beginning of the file.

w+ - It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn't overwrite the previously written file. It creates a new file if no file exists. The file pointer exists at the beginning of the file.

a+ - It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.

Creating a File :

If you want to create a file , You must use 'x' for access mode. Suppose i want to create a file with file name : Console on my desktop .

Syntax : open(file-path , mode)

f = open(r'C:\Users\abhi\Desktop\Console.txt','x')  #will create a file 'Console' in desktop.

Note:It will throw error if duplicate file is created with same name.

f = open(r'C:\Users\abhi\Desktop\Console.txt','x')
---------------------------------------------------------------------------
FileExistsError                           Traceback (most recent call last)
<ipython-input-7-37a6538c42b6> in <module>
----> 1 f = open(r'C:\Users\abhi\Desktop\Console.txt','x')

FileExistsError: [Errno 17] File exists: 'C:\\Users\\abhi\\Desktop\\Console.txt'

Writing in a file with 'w' :

It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name.

let's start with a new file that we have created and is empty by now.

To write in a we must open this file with right access mode. w or a is the right access mode for writing in an empty File.

f = open(r'C:\Users\abhi\Desktop\Console.txt','w')   #opening a file with access mode
f.write('''The file handling plays an important role when the data needs to be stored permanently into the file. 
A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.''')  #file operation
f.close()   #closing a file

If we write anything again in the same file , data in file will overwrite. for Example:

In [9]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','w')   #opening a file with access mode
f.write('''The file-handling implementation is slightly lengthy or complicated in the other programming language,
but it is easier and shorter in Python.''')  #file operation
f.close()   #closing a file

'w' overwrote data in Console File.

Writing in a file with 'a' :

a - It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists any. It creates a new file if no file exists with the same name.

let's try to append data in our 'Console' File :

In [10]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','a')
f.write("To perform any operation in file , we must need to open the file.")
f.close()

Reading in a file with 'r' :

It opens the file to read-only mode.The file is by default open in this mode if no access mode is passed.

Let's try to read our Console file.

In [11]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','r')
data = f.read()
f.close()

print(data)
The file-handling implementation is slightly lengthy or complicated in the other programming language,
but it is easier and shorter in Python.To perform any operation in file , we must need to open the file.

To convert data written in Console in upper case :

In [12]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','r')
data = f.read()
f.close()

data = data.upper()

f = open(r'C:\Users\abhi\Desktop\Console.txt','w')
f.write(data)
f.close()

Read file with loop :

In [15]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','r')  #opening file with read permission
for i in f:
    print(i)   #prints each line
The file-handling implementation is slightly lengthy or complicated in the other programming language,

but it is easier and shorter in Python.To perform any operation in file , we must need to open the file.

Read lines of a file :

The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.

In [17]:

f = open(r'C:\Users\abhi\Desktop\Console.txt','r') 
firstline = f.readline()
print(firstline)
f.close()
The file-handling implementation is slightly lengthy or complicated in the other programming language,

Introduction to OS Module :

To use os module in python , we must first import it.

Renaming File :

To rename a file, rename() method is used.

In [ ]:

os.rename(current name , new name)

In [ ]:

import os    #importing os module
os.rename(r'C:\Users\abhi\Desktop\Console.txt', r'C:\Users\abhi\Desktop\Consoleflare.txt')

Removing the file :

The os module provides the remove() method which is used to remove the specified file. The syntax to use the remove() method is given below.

In [ ]:

os.remove(file)

In [28]:

import os
os.remove(r'C:\Users\abhi\Desktop\one.txt')

Creating a new directory or Folder :

To create a new Directory or folder , we use mkdir() method.

In [29]:

import os 
os.mkdir(r'C:\Users\abhi\Desktop\files')

The folder that has been created is empty by now, but we can create multiple files in by simply creating a loop . Suppose i want to create 100 files in file folder , our code may look like this :

import os
for i in range(10):
    f = open(r'C:\Users\abhi\Desktop\files\FILE'+str(i),'x')

Assignment :

1.Write a Python program to read an entire text file. 2.Write a Python program to read an entire text file. 3.Write a python program to find the longest words in a file. 4.Write a Python program to read a random line from a file. 5.Write a Python program to count the number of lines in a text file.

Last updated