PDA Assignments
  • Python For Data Analytics
    • 1.Python
      • 1.Python Documents
        • 1.Data Types
        • 2.Variables In Python
        • 3.Operators In Python
        • 4.User Input In Python
        • 5.TypeCasting In Python
        • 6.Strings In Python
        • 7.Conditional Statements In Python
        • 8.Branching using Conditional Statements and Loops in Python
        • 9.Lists In Python
        • 10.Sets In Python
        • 11.Tuples In Python
        • 12.Dictionary In Python
        • 13.Functions In Python
        • 14.File Handling In Python
        • 15.Numerical Computing with Python and Numpy
      • 2.Python Assignments
        • Data Type & Variables
        • Operators Assignment
        • User Input & Type Casting
        • Functions- Basic Assignments
        • String Assignments
          • String CheatSheet
        • Conditional Statements Assignments
        • Loops Assignments
        • List Assignments
          • List Cheatsheet
        • Set Assignments
          • Sets Cheatsheet
        • Dictionary Assignments
          • Dictionary Cheatsheet
        • Function Assignments
        • Functions used in Python
      • 3.Python Projects
        • Employee Management System
        • Hamming distance
        • Webscraping With Python
          • Introduction To Web Scraping
          • Importing Necessary Libraries
          • Basic Introduction To HTML
          • Introduction To BeautifulSoup
          • Flipkart Web Scraping
            • Scraping Step By Step
        • Retail Sales Analysis
        • Guess the Word Game
        • Data Collection Through APIs
        • To-Do List Manager
        • Atm-functionalities(nested if)
        • Distribution of Cards(List & Nested for)
        • Guess the Number Game
      • 4.Python + SQL Projects
        • Bookstore Management System
    • 2.Data Analytics
      • 1.Pandas
        • 1.Pandas Documents
          • 1.Introduction To Pandas
          • Reading and Loading Different Data
          • 2.Indexing and Slicing In Pandas
          • 3.Joining In Pandas
          • 4.Missing Values In Pandas
          • 5.Outliers In Pandas
          • 6.Aggregating Data
          • 7.DateTime In Pandas
          • 8.Validation In Pandas
          • 9.Fetching Data From SQL
          • 10. Automation In Pandas
          • 11.Matplotlib - Data Visualization
          • 12. Seaborn - Data Visualization
          • 13. Required Files
        • 3.Pandas Projects
          • Retail Sales Analysis
            • Retail Sales Step By Step
          • IMDB - Dataset Analysis - Basic
        • 2. Pandas Assignments
          • 1. Reading and Loading the Data
          • 2. Data frame Functions and Properties
          • 3. Series - Basic Operations
          • 4. Filtering in Pandas
          • 5. Advance Filtering
          • 6. Aggregate Functions & Groupby
          • 7. Pivot Tables
          • 8. Datetime
          • 9. String Functions
Powered by GitBook
On this page
  • What is File Handling ?
  • Opening a file :
  • Types of Access modes :
  • Creating a File :
  • Writing in a file with 'w' :
  • Writing in a file with 'a' :
  • Reading in a file with 'r' :
  • To convert data written in Console in upper case :
  • Read file with loop :
  • Read lines of a file :
  • Introduction to OS Module :
  • Renaming File :
  • Removing the file :
  • Creating a new directory or Folder :
  • Assignment :
  1. Python For Data Analytics
  2. 1.Python
  3. 1.Python Documents

14.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 deskt

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

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.

Previous13.Functions In PythonNext15.Numerical Computing with Python and Numpy

Last updated 2 years ago