0% found this document useful (0 votes)
15 views

File Handling Easy Notes

Uploaded by

monish.d.v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

File Handling Easy Notes

Uploaded by

monish.d.v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.

XII – COMPUTER SCIENCE (083) - FILE HANDLING

CSV file (Comma Separated


Files Text file Binary file
Values)
pickle
1. Module
- pickling – python object to binary. csv
unpickling – binary to python object.
 It is like a text file and
 It is human readable.  It is non-human readable
human readable.
2. Definition  Data will be stored in ASCII or  Data stores in terms of bytes
 Data will be stored in
Unicode Characters. (0, 1).
tabular form.

3. Extension .txt .dat .csv

 r – read only, File not exists it returns


Error. (Beginning).
 w – write only, File not exists it
creates a new file. (Beginning). rb, wb, ab, rb+, wb+, ab+
 a – append only, File not exists it
creates a new file. (End). r, w, a, r+, w+, a+
4. Modes
 r+ - read and write, File not exists it
returns Error. (Beginning).
 w+ - write and read, File not exists it
creates a new file. (Beginning).
 a+ - append and read, File not exists
it creates a new file. (End).

1
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

 read() – To read the entire data  load() – To load the data from  reader() – To read the
character by character. binary file. data from csv file.
 read(n) - To read the number of  Syntax:-  Syntax:-
characters. Data_object_name = Reader_object =
5. Reading  read().split() – To read the entire pickle.load(fileobject) csv.reader(fileobject)
Methods data word by word.
 readline() – To read the data line by
line.
 readlines() – To read the entire line
by list of elements.
 writer() – To write the
data in csv file.
 write() – To write the data character  dump() – To dump the data in
 Syntax:- Writer_object
6. Writing by character. binary file.
= csv.writer(fileobject)
Methods  writelines() – To write the list of  Syntax:-
 writerow() – single row
data. pickle.dump(dataobject, file object)
 writerows() – Multiple
rows
 tell() – it tells the current cursor position. Default position is 0. Syntax:- fileobject.tell()
7. Other
 seek() – It is used to change the cursor position. Syntax:- fileobject.seek(offset [ , referencepoint ] )
Methods
Default reference point is 0 - (beginning), 1 – (last cursor position), 2 – (end).

Open the file: - fileobject = open(“filename”,”filemode”) (Or) with open(“filename”,”filemode”) as fileobject:


Close the file: - fileobject.close()
2
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

1. Write a function, vowel_Count() in Python 2. Write a function count Dwords() in 3. Write a function in Python to read a text
that counts and displays the number of Python to count the words starting with a file, Alpha.txt and displays those lines
vowels in the text file named Poem.txt. letter ‘a’ in a text file ” Details . txt”. which begin with the word ‘You’.
def vowel_Count(): def Dwords(): def sample():
f=open(“Alpha.txt”,’r’) f=open("details.txt") f = open(“Alpha.txt”, ‘r’)
c=0 c=0 for i in f.readlines():
for i in f.read(): for i in f.read().split(): x=i.split()
if i in “aeiouAEIOU”: if i[0] == ‘a’: if x[0]==”You”:
c=c+1 c+=1 print(x)
print(c) print(c) f.close()
f.close() f.close()

3
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

4. Write a function, c_words() in Python that 5. Write a user defined function 6. Write a function to display those lines
separately counts and displays the number countwords() to display the total number which start with the letter ‘S’ from the text
of uppercase and lowercase alphabets in a of words present in the file from a text file file “Notes.txt”.
text file named Words.txt. named “Quotes.txt”. def count_lines():
def c_words(): def countwords(): f = open(“Notes.txt”)
f = open(“Words.txt”, ‘r’) f = open(“Quotes.txt”, ‘r’) x = f.readlines()
x = f.read() x = f.read().split() for i in x:
L=U=0 c=0 if i[0] == ‘S’:
for i in x: for i in x: print(i)
if i.islower(): c = c+1 f.close()
L=L+1 print(c)
elif i.isupper(): f.close()
U=U+1
print(L,U)

4
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

1.Consider a file, SPORT.DAT, containing records of the following 2. A Binary file, CINEMA.DAT has the following structure:
structure: [SportName, TeamName, No_Players] {MNO: [MNAME, MTYPE]}
Write a function, copyData(), that reads contents from the file Where MNO – Movie Number, MNAME – Movie Name and
SPORT.DAT and copies the records with Sport name as “Basket
MTYPE is Movie Type.
Ball” to the file named BASKET.DAT. The function should return
Write a user defined function, findType(mtype), that accepts mtype
the total number of records copied to the file BASKET.DAT. as parameter and displays all the records from the binary file
Answer: CINEMA.DAT, that have the value of Movie Type as mtype.
import pickle Answer:
def copyData( ):
import pickle
f1 = open (“ Sport.dat” , “rb”)
f2 = open (“Basket.dat”, “wb”) def Searchtype(mtype):
c=0 f = open (“cinema.dat”, “rb”)
try: try:
while True:
while True:
x = pickle.load( f1 )
if x[0] == “Basket Ball”: x = pickle.load(f)
pickle.dump(x , f2) if x[2] == mtype:
c+=1 print(x)
except: except:
f1.close()
f2.close() f.close()
return c

5
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

3. Consider a binary file, items.dat, containing records stored in 4. A binary file, EMP.DAT has the following structure: [Emp_id,
the given format: {item_id: [item_name, amount]} Name, Salary]
Write a function, Copy_new(), that copies all records whose Where Emp_id: Employee id, Name: Employee Name and Salary:
amount is greater than 1000 from items.dat to new_items.dat. Employee Salary
Answer: Write a user defined function, disp_Details(), that would read the
import pickle contents of the file EMP.DAT and display the details of those
def Copy_new( ): employees whose salary is below 25000.
f1 = open (“items.dat” , “rb”) Answer:
f2 = open (“new_items.dat”, “wb”) import pickle
try: def disp_Details():
try:
while True:
with open(“EMP.DAT”,’rb’) as f:
x = pickle.load( f1 )
x = pickle.load(f)
for i,j in x.items(): for i in x:
if i[1] > 1000: if i[2] < 25000:
pickle.dump(x, f2) print(i)
except: except:
f1.close() print(“File Not Found”)
f2.close()

6
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

1. Sangeetha is a Python programmer working in a computer Answer:


hardware company. She has to maintain the records of the import csv
peripheral devices. She created a csv file named Peripheral.csv, def Add_Device():
f = open(“Peripheral.csv”, ’a’, newline=” “)
to store the details.
x = csv.writer(f)
The structure of Peripheral.csv is: [P_id, P_name, Price] P_id = int( input())
Where P_name = input()
P_id is Peripheral device id (integer), Price = int( input())
P_name is Peripheral device name (String) and y = [P_id, P_name, Price]
Price is Peripheral device price (integer) x.writerow(y)
Sangeetha wants to write the following user defined functions: f.close()
Add_Device(): to accept a record from the used and add it to a
def Count_Device():
csv file, Peripheral.csv f = open(“Peripheral.csv”, ‘r’)
Count_Device(): To count and display number of peripheral x = csv.reader(f)
devices whose price is less than 1000. y = list(x)
c=0
for i in y:
if int(i[2]) < 1000:
c = c+1
print(c)
f.close()

7
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

Answer:
2. Ajay is a Python programmer working in a school. For the
Annual Sports Event, he has created a csv file named Result.csv, import csv
to store the results of students in different sports events. The def Accept():
structure of Result.csv is: f = open(“Result.csv”, ’a’, newline=” “)
[St_Id, St_Name, Game_Name, Result] x = csv.writer(f)
St_Id= int (input ())
Where
St_Name= input()
St_Id is Student ID (integer) Game_Name = input()
ST_name is Student Name (string) Result = input()
heading=[“St_id”,”St_Name”,”Game_Name”,”Result”]
Game_Name is name of game in which student is
y = [St_id, St_Name, Game_Name, Result]
participating(string) Result is result of the game whose value can
x.writerow(heading)
be either 'Won', 'Lost' or 'Tie'
x.writerow(y)
For efficiently maintaining data of the event, Ajay wants to write f.close()
the following user defined functions:
def CountRecord():
Accept() – to accept a record from the user and add it to the file
Result.csv. The column headings should also be added on top of f=open("Result.csv","r")
the csv file. x=csv.reader(f)
CountRecord() – to count the number of records present in the y=list(x)
csv file named ‘Result.csv’.
print(len(y))
As a Python expert, help him complete the task. f.close()

8
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE
VELAMMAL NEW GEN SCHOOL – SHOLINGANALLUR.
XII – COMPUTER SCIENCE (083) - FILE HANDLING

Answer:
3. Write a Program in Python that defines and calls the following
import csv
user defined functions:
def add():
(i) add() – To accept and add data of an employee to a CSV f=open("employee.csv", "a", newline=” “)
file ‘employee.csv’. Each record consists of a list with field x=csv.writer(f)
elements as eid, name and salary to store employee id, eid=int(input( ))
employee name and employee salary respectively. name=input( )
salary =int(input( ))
(ii) search()- To display the records of the employee whose
y=[eid, name, salary]
salary is more than 40000.
x.writerow(y)
f.close()
def search():
f=open("employee.csv", "r”)
x=list(csv.reader(f))
for i in x:
if int(i[2]) > 40000:
print(i[0], i[1], i[2])
else:
print("Record not found")
f.close()

9
C. MANIMARAN., MCA., M.Phil., B.Ed,
PGT – COMPUTER SCIENCE

You might also like