CS - File Handling
CS - File Handling
FILE HANDLING
What is File?
A file is a sequence of bytes on the disk where a group of related data is stored. It is a named location on a
backup storage media where data are permanently stored.
In an interactive program, when user inputs data, it is stored in the main memory (RAM) which is volatile
(data would be lost when the power supply is off). The main objective of handling file is to store data
permanently in a backup device so that it can be accessed latter.
File handling in Python enables us to create, update, read, and delete the files stored on the disk through
program.
Types of File
Text file: data are stored in a platform-dependent encoding format (ASCII or Unicode, UTF8 etc).
This mode is about conversion of line endings.
Binary file: data are stored in the same format as in memory (raw). No translation or encoding
applied while rendering data.
CSV file: (Comma Separated Values file) is a type of plain text file that uses specific structuring to
arrange tabular data.
Text file Binary file CSV file
It is capable to handle textual It is capable to handle binary It is very common format and
data. data in the same format as in platform independent.
memory.
It consists of series of lines of a It consists of data with a It consists of plain text with a
set of letters, numbers or specific pattern without any list of data with a delimiter.
symbols (String) delimiter.
Any text editors like notepad can No specific programs can be It can be read using text editors
be used to read them. used to read them, python like notepads and spreadsheet
provides functions to read data. software.
Every line ends with EOL. There is no specific EOL Every line ends with EOL.
character.
Conversion taken place from No conversion taken place Conversion taken place from
ASCII/UNICODE to Binary ASCII/UNICODE to Binary
while presenting while presenting
Operations on a file
File handling takes the following operations in sequence
Opening of a file Read or write (perform operation) Closing of the file
C (Root Directory)
:
demo
Opening a file
Syntax:
Fileobject = open(“filename”,”mode”)
Example:
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("test.txt",'wb') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Closing a file
File must be closed when all operations are over. Closing a file will free up the resources that were tied with
the file and is done using Python close() method.
Syntax:
Fileobject.close()
However, if a file is opened using “with” statement, the file is implicitly closed when the block of statement
is over. For ex.
with open("filename",”mode”) as f:
# perform file operations
This ensures that the file is closed when the block inside with is exited. We don't need to explicitly call the
close() method. It is done internally.
Example#1
Write a program to read the contents of a text file.
f=read(„story.txt‟,‟r‟)
d=f.read()
print(d)
f.close()
Example#2
Write a program to read the contents of a text file and print character by character.
f=read(„story.txt‟,‟r‟)
d=f.read()
for i in d:
print(i)
f.close()
Example#3
Write a program to read the contents of a text file and print words.
f=read(„story.txt‟,‟r‟)
d=f.read()
w=d.split()
for i in w:
print(i)
f.close()
Example#4
Write a program to read the contents of a text file and print line by line.
f=read(„story.txt‟,‟r‟)
lns=f.readlines()
for ln in lns:
print(ln)
f.close()
OR
Std. XII (SCIENCE) 4
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
f=open("story.txt","r")
while True:
a=f.readline()
if len(a)<=0:
break
print(a)
f.close()
Example#5
Write a program to read data from keyboard and store in a file.
f=read(„story.txt‟,‟w‟)
if not f:
print(“File can‟t be created”)
else:
nm=input(“Enter your name:”)
f.write(nm)
age=input(“Enter your age:”)
f.write(age)
f.close()
EXERCISE
1. Write a program to accept strings and store in a text file named „myfile1.txt‟ in 2
d:\<yourname> folder.
2. Write a program to read the contents of the file “myfile1.txt”. 2
3. Write a program to read the 1st 20 characters of the file “myfile1.txt”. 2
4. Write a program to read the contents of the file “myfile1.txt” line by line. 2
5. Write a function in PYTHON to count the no. of vowels (ignore case) present in a text file " 2
myfile1.txt ".
6. Write program to count no. of words in a text file named “myfile1.txt”. 2
7. Write program to read the content of a text file myfile1.txt, and display the words with 3 2
character in length.
8. Write a program to read contents of a text file named myfile1.txt, count and display the 2
occurrence of a given word. Note :
‐ The word should be an independent word
‐ Ignore type cases (i.e. lower/upper case)
9. Write a program that reads the contents of a text file story.txt and counts the words You and 2
Me (not case sensitive)(not whole word)
10. Write a program in PYTHON to read the content of a text file "DELHI.TXT' and display all 2
those lines on screen, which are either starting with 'D' or starting with 'M'.
11. Write a program in PYTHON to count the no. of vowels (ignore case) present in a text file 2
"STORY. TXT" line wise.
12. Write a program in PYTHON to count the no. of lines, tabs, whitespaces, upper cases, 2
lowercase and digits present in a text file "STORY. TXT".
13. Write a function in PYTHON to read the content of a text file "DELHI.TXT' and copy only 2
those lines started with „I‟ into a new file named „NewDelhi.txt‟
Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document
formats like Word or PDF.
Binary files are less in size as compared to text file for the same data, due to its‟ internal representation. For
example if we wants to store 234556 in a text file it occupied 6 bytes (a byte for each digits), where as in
binary mode it is 4 byte only, because in Memory it is represented as integer.
In Text mode, data are stored in a platform-dependent encoding format (ASCII or Unicode, UTF8 etc). This
mode is about conversion of line endings.
On the other hand, Binary mode data are stored in the same format as in memory (raw). No translation or
encoding applied while rendering data.
The pickle module
“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and
“unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is
converted back into an object hierarchy. Pickling is alternatively known as “serialization”, “marshalling”.
The reverse process, which takes a stream of bytes and converts it back into a data structure, is called
deserialization or unmarshalling.
Pickle module has the following methods to handle file. You have to import the module before calling the
methods.
Example #2
Write a python program to read data earlier stored in the binary file stud.dat.
sid,sname,sclass,section
import pickle
f=open(“stud.dat”,”rb”)
try:
while True:
d=pickle.load(f)
print(d)
except:
pass
f.close()
Example:
import csv
f=open("d:/book1.csv")
csv_reader = csv.reader(f)
for row in csv_reader:
print(row)
f.close()
Note : Other than comma (,) , the separator character or delimiter may be the tab, colon (:) and semi-colon
(;) characters etc. Properly parsing a CSV file requires us to know which delimiter is being used.
csv_reader = csv.reader(cf,delimiter=‟:‟)
Example #
import csv
with open(r'd:\samplecsv2.csv', mode='w') as f:
fwriter = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
fwriter.writerow(['Name', 'Gender', 'City'])
fwriter.writerow(['SangramKishor Dash', 'Male', 'Berhampur'])
fwriter.writerow(['Nigam Prasad', 'Male', 'Bhubaneswar'])
fwriter.writerow(['ArpitaKumari Mishra', 'Female', 'Cuttack'])
Std. XII (SCIENCE) 9
MODERN OXFORD PUBLIC SCHOOL, BAM [CS MATERIAL]
Example #2
import csv
with open(r'd:\samplecsv3.csv', 'w') as fc:
fieldnames = ['Name', 'Gender', 'City']
writer = csv.DictWriter(fc, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'Santosh Kumar Panda', 'Gender': 'Male', 'City': 'Berhampur'})
writer.writerow({'Name': 'Ganesh Pradhan', 'Gender': 'Male', 'City': 'Kolkota'})
1 Write a program in python to write the STUDENT data in a csv file named “student.csv” with 2
following structure. [sid,sname,Sclsss,eng,maths]
2 Write a program in python to read and display the sid and name of students who has obtained 2
>50 in English form a csv file “student.csv”.
3 Write a program in python to read and display the details with total and percentage of mark 2
who has obtained more than 60% form a csv file “student.csv”.