Class XII - File Handling Text Files
Class XII - File Handling Text Files
Class XII
What is a data file and why we need to work with files in Python—
Data File - Data stored on permanent storage in computer is called data file. Each data file has a specific name.
When a program runs, it generally stores its data in RAM, which is volatile memory. Means data is not
permanently stored. In such programs, data related to program gets washed away as soon as the program ends.
But what if you want to permanently store data of a program? To be able to do so, we need to store it on
permanent storage. There are generally two options to permanently store your data-
1. Using Database- we studied what is database and how to insert/modify data into database using SQL in
previous class. We can connect python program to database and store program data into database. We
will study this later.
2. Using data files - We can store program data into permanent storage using data files.
File Operations –
1. Text File – Data is stored in the form of human readable text (either ASCII or UNICODE)
2. Binary File - Data is stored in binary form which is not human readable.
3. CSV(Comma Separated Values File) : Data values are separated by commas. It can be viewed in tabular
form.
Opening and Closing Files – Before doing any other operation on file, we need to open it in our program.
File Handle – It is an identifier that is linked to file after opening it. File handle is used for further working with
the file.
File Mode –It is the mode in which you want to open a file. There are 3 basic file modes – r (read only), w (write
only) and a (append)
Example—
Let’s say we want to open Employees.txt in read mode. Following statement will do the work –
MyFile = open(“Employee.txt”,”r”)
<File_object>.close()
Example –
MyFile.close()
1. r – (read mode)
To open a file in read only mode.
Writing is not allowed
If file does not exist, It gives error
2. w—(Write Mode)
To open a file in write only mode
reading is not allowed
If file does not exist, new blank file is created.
If file exist already, existing data is truncated/deleted.
3. a – (Append Mode)
To open a file in append mode
Reading is not allowed
If file not exist, new blank file is created.
If file exist already, existing data is NOT truncated/deleted.
4. r+ – (Read and Write mode)
Both reading and writing is allowed
If file does not exist, It gives error
5. w+ – (Write and Read mode)
Both reading and writing is allowed
If file does not exist, new blank file is created.
If file exist already, existing data is truncated/deleted.
6. a+ – (Append and Read mode
Both reading and writing is allowed
If file not exist, new blank file is created.
If file exist already, existing data is NOT truncated/deleted.
STEPS—
1. read(n) - read n number of characters from file. But if n is not given, it will read entire file. It returns
data in the form of string.
2. readline(n) – It will read one line at a time, if n is specified, it will read first n characters of each line.
It returns data in the form of string.
3. readlines() – to read all lines of a file in a LIST. It returns a List.
Exxamples—
Answer -
MYFILE = open("Student.txt","r")
A = MYFILE.read() I am a dummy file
print(A) >>>
MYFILE.close() Output
2. Write a program to read first 5 characters from a file and print it.
Suppose File content is as below–
ANSWER -
MYFILE = open("Student.txt","r")
A = MYFILE.read(5) I am
print(A) >>>>>>
MYFILE.close() Output
3. Write a program to read a file Student.txt character wise, means reading should be done one
character at a time and print its each character in new line.
Suppose File content is as below–
ANSWER—
MYFILE = open("Student.txt","r")
A = MYFILE.read(1) d
while A: u
print(A) m
A = MYFILE.read(1)
m
MYFILE.close()
y
Output
>>>
STEPS—
1. write(<str>) - write string <str> into file. It does not insert newline(‘\n’) so newline has to be
inserted manually..
2. writelines(<list>) – to write all lines of a List <list> into file.
Example—
Above program will create a file “output.txt” and write the contents into it.
Here we have manually inserted newline (“\n”) at the end of each line because write() or writelines()
functions do not automatically insert newline.
Pathname: full name of a file along with directory structure is called its path or pathname.
Absolute Path: Path of a file from top level directory(root) is called Absolute path.
For example—
E:\MyData\Python\Files\Student.txt
Relative Path: Path of a file with respect to current working directory (CWD) is called relative path.
For Example—
.\Files\Student.txt
1. Write a program to read data from a file using absolute path of file.
print(S) Output
File.seek( n,m)
1 – Current position
2. Write a program to read a file INPUT.txt and copy lines starting with letter ‘D’ to another file
OUTPUT.txt.
File1 = open("Input.txt","r")
File2 = open("Output.txt","w")
for LINE in File1: Output
if LINE[0] == 'D':
File2.write(LINE)
File2.write('\n')
File1.close()
File2.close()
import os
FH_I = open("INPUT.txt","r") >>>>>>
FH_O = open("OUTPUT.txt","w")
for LINE in FH_I:
WORDS = LINE.split() Output
L = len(WORDS)
4. Write a program to delete a line containing word ‘Password’ from a file input.txt
FILE.close()
TEMP.close()
os.remove("INPUT.txt")
os.rename("Temp.txt","INPUT.txt")
STANDARD INPUT/OUTPUT and ERROR STREAMS
Standard Output Stream : It is a file attached to Standard Output device. Whatever is written into this
file is displayed on monitor.
To use these files, we have to import sys module.
File Name is sys.stdout
Standard Input Stream : It is a file attached to Standard Input device (Keyboard). Whatever is written
into this file will be taken as input.