Python File Handling Notes for class 12 

 

Data File Handling in Python

Data maintained inside the files is termed as persistent data. It means it is permanent in nature.
Python allow us to read data from and save data to external text files permanently on secondary storage media.

Before we start working with a file, first we need to open it. After performing the desirable operation, it needs to be closed so that resources that are tied in the file are freed.

Data File handling takes place in the following order.

1- Opening a file.
2- Performing operations (read, write) or processing data.
3- Closing the file.

 

We can process file in several ways, such as:

 

-> Creating a file

->Traversing a file for displaying data on screen

->Appending data in a file

->Inserting data in a file

->Deleting data in from a file

->Creating a copy of a file

->Updating data in a file

 

Types of File in Python:

Before we discuss file operation we should be aware of the file types. Python allows us to create and manage two types of data files.

1- Text file

2- Binary file

File Modes

Mode

Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. If the specified file does not exist, it will generate FileNotFoundError.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. (+) The file pointer will be at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, it creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

 

Python Data File Handling

operations on text file

A text file consists of a sequence of lines. A line is a sequence of characters, stored on permanent storage. In a text file, each line is terminated by a special character, known as End Of Line (EOL). Text file can be created using any text editor. Ex. Myfile.txt.

 

Opening a text file: Open ()

When we want to read or write a file, we must have to open is first. Open () function takes the name of a file as the first argument. The second argument indicates the mode of accessing the file.

Syntax:

<file variable>=open(file name, access mode)

Modes for opening a file:

read(r) : to read the file

write(w): to write the file

append(a):  to write at the end of file

 

Ex:

>>> f=open(‘myfile.txt’)

>>> print(f)

 

Output:

<_io.TextIOWrapper name='myfile.txt' mode='r' encoding='cp1252'>

 

Python File Handling notes for CBSE class 12 Computer Science

Closing file: close()

Syntax:  file_Object.close()

Example:

f=open('myfile.txt')
print("The file which is to be open using the given command is:",f.name)
f.close()

Output:

The file which is to be open using the given command is: myfile.txt

 

Properties of File Object:

 

name: shows the file name of opened file

mode: shows Mode in which the file gets opened

readable: returns Boolean value, which indicates whether the file is readable or not

closed: returns Boolean value, which indicates whether the file is closed or not

 

Example:

f=open('myfile.txt', 'w')
print("Name of File:",f.name)
print("Mode of File:",f.mode)
print("File readable :",f.readable())
print("File closed:",f.closed)
f.close()
print("File closed:",f.closed, f.name)

 

 

Output:

Name of File: myfile.txt
Mode of File: w
File readable : False
File closed: False
File closed: True myfile.txt

 

Python File Handling notes for CBSE class 12 Computer Science

Reading form a file:

We can read character data from text file by using the following read methods:

 

read(): To read the entire data from the file; starts reading from the cursor up to the end of the file.

Synatx:

file_Object.read()

Example:

The text file named myfile.txt is already stored in my local disk with the data shown in image.

CBSE file handling

 

f=open('myfile.txt', 'r')
data=f.read()
print(data)
f.close()

 

Output:

== RESTART: C:/Users/ATC/AppData/Local/Programs/Python/Python38-32/filehandling.py =
Hello,
Welcome to the CBSE class 12 students
Having computer science with python
You are learning Python file handling
>>>

read(n): To read ‘n’ characters from the file, starting from the cursor.

Example: Here we will read only first 21 characters from the file.

f=open('myfile.txt', 'r')
data=f.read(21)
print(data)
f.close()

 

Output:

Hello,
Welcome to the

 

readline(): To read only one line from the file; starts reading from the cursor up to, and including, the end of line character.

readlines(): To read all lines from the file into a list; starts reading from the cursor up to the end of the file and returns a list of lines.

Writing to the text file: 

There are two methods in Python to write data to the text file. 

1. write( ): This method takes a string as a parameter and writes it in the file. As we discussed about the file mode earlier, we use ‘w’ access mode to write date to the text file.

Syntax: fileObject.write (string)

Example:

f=open('myfile.txt', 'w')
f.write("these are file handing notes for class 12")
print("Your data is written to the text file successfully")
f.close()

 

Output:

= RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python311/file_handling.py
Your data is written to the text file successfully

 

 

2. writelines ( ): This method is used whenever we have to write a sequence of data types or string. 

 

Syntax: fileObject.write (sequence)

 

Example:

f=open('myfile.txt', 'w')
list=["Class 12","File Handling Notes\n", "You are learning\n", "Writing to the text file"]
f.writelines(list)
print("Your data is written to the text file successfully")
f.close()

 

Python File Handling notes for CBSE class 12 Computer Science

Appending to the text file: 

When ‘w’ access mode is used in file handing it overwrites or replace the previous written data. As you already know about append which means ‘to add data at end of file’, we use access mode ‘a’ to insert data to the text file at the end.

 

Example:

f=open('myfile.txt', 'a')
f.write("Class 12\n")
f.write("File Handling Notes\n")
f.write("You are learning\n")
f.write("Writing / appending to the text file")
print("Your data is written to the text file successfully")
f.close()

 

You just check if the data is successfully written to the file or not by reading the file again. Now lets check.

f=open("myfile.txt", "r")
data=f.read()
print(data)
f.close()

 

Output:

= RESTART: C:/Users/lenovo/AppData/Local/Programs/Python/Python311/x.py
Class 12
File Handling Notes
You are learning
Writing / appending to the text file

 

Appending_Text_File

 

Hope you understand  about writing, reading and appending files in python. Let us take an example in which you get Roll Number, Name and Marks of 5 Students from user and store this detail in file ‘report.txt’. 

 

f=open("report.txt","w")
for i in range(5):
    roll_no=int(input("Roll No:"))
    name=input("Name:")
    marks=int(input("Marks:"))
    data= str(roll_no)+ "|" +name+ "|"+str(marks)
    f.write(data)
    f.write("\n")#To display data in next line
f.close()

 

Output:

Roll No:1
Name:"Devkaran"
Marks:28
Roll No:2
Name:"Uday Pratap"
Marks:25
Roll No:3
Name:"Pratiksha"
Marks:23
Roll No:4
Name:"Aayushi"
Marks:21
Roll No:5
Name:"Pallavi"
Marks:21
>>>

 

python file handling

Final Data in Text file:

File handling in Python

 

You must check :

Text File MCQs for Class 12 

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved
error: Content is protected !!