0% found this document useful (0 votes)
77 views120 pages

Class 12 CS File Handling

hi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views120 pages

Class 12 CS File Handling

hi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 120

DELHI PUBLIC SCHOOL

NACHARAM
SUB: CLASS XII COMPUTER SCIENCE
SUB CODE: 083
FILE HANDLING

PRASAD N
PGT COMPUTER
SCIENCE
DATA FILES
THE DATA FILES ARE THE FILES THAT
STORES DATA PERTAINING TO A SPECIFIC
APPLICATION, FOR LATER USE.

DATA FILES CAN BE STORED IN TWO WAYS:


1. TEXT FILES

2. BINARY FILES

3. CSV (COMMA SEPARATED VALUES) FILES


Need for a data file:
Text Files:

A text file stores information in ASCII or Unicode characters.

In text file each line of text is terminated with a special character

known as EOL ( End Of Line) character.

In Python by default this EOL character is the newline character (‘\

n’)
Binary Files:
A BINARY FILE IS JUST A FILE THAT CONTAINS INFORMATION IN
THE SAME FORMAT IN WHICH THE INFORMATION IS HELD IN
MEMORY
▪ IN BINARY FILE THERE IS NO DELIMITER FOR A LINE
▪ BINARY FILES ARE FASTER AND EASIER TO READ AND WRITE
▪ BINARY FILES ARE THE BEST WAY TO STORE PROGRAM
INFORMATION
OPENING AND CLOSING FILES

THE MOST BASIC FILE MANIPULATION TASKS INCLUDE


ADDING, MODIFYING OR DELETING DATA IN A FILE,
WHICH IN TURN INCLUDE ANY ONE OR COMBINATION
OF THE FOLLOWING OPERATIONS:
⮚ REDING DATA FROM FILES
⮚ WRITING DATA TO FILES
⮚ APPENDING DATA TO FILES
To access file:

Absolute path:

Relative path:
Opening Files:

⮚Python provides built-in functions to perform file manipulation like adding, deleting

and modifying

⮚First we need to open the file first

syntax: <file-name> = open (“file-path”, “mode”)

Example: myfile =open(“Sample.txt”,”r”)


Note: if no mode is given , file will opened in read mode
Reading Files:
1. read()
2. readline()
3. readlines()

Note: i. f1=open(“c:\\temp\\sample.txt”,”r”).read()
print(f1)
ii. f1=open(r “c:\temp\data.txt”,”r”)
METHOD SYNTAX DESCRIPTION

read() <filehanlde>.read(n) Reads atmost n bytes;


If no n is specified, reads the
entire file

readline() <filehanlde>.readline(n) Reads a line of input;

readlines() <filehandle>.readlines() Reads all lines and returns them


in a list
Writing onto files:

Creating a file:
f1=open("Sample.txt","w")
f1.write("how are you")
f1.close()
Writing onto files:

Example : Create a file and insert some data

f1=open(“sample.txt”,”w”
)
for i in range(5):
name=input(“enter ur
name”)
f1.write(name)
f1.close()
Example 1: Reading a file’s entire content:

myfile=open(“license.txt”,”r”)
str=myfile.read()
Example 2: Reading a file’s first 20 bytes and print it:
print(str)
myfile.close() myfile=open(“license.txt”,”r”)
str=myfile.read(20)
print(str)
myfile.close()
Example 3: Reading a file’s first 20 bytes and then reading some more bytes
from the last position read:

f1=open(“license.txt”,”r”)
r1=f1.read(20)
print(r1)
r2=f1.read(50)
print(r2)
f1.close()
Example 4: Reading file using readline()

f1=open(“LICENSE.txt”,”r”)
r1=f1.readline() Example 5: Reading file’s first 20 bytes using readline()

print(r1) f1=open(“LICENSE.txt”,”r”)
f1.close() r1=f1.readline(20)
print(r1)
f1.close()
Example 6: Reading a file’s first 3 lines – line by line

myfile=open(“license.txt”,”r”)
str=myfile.readline()
print(str,end=‘ ‘)
str=myfile.readline()
print(str,end=‘ ‘)
str=myfile.readline()
print(str,end=‘ ‘)
myfile.close()
Example 7: Reading file using readline()

f1=open(“LICENSE.txt”,”r”)
r1=f1.readline() Example 8: Reading a complete file line by line

print(r1)
f1=open(“LICENSE.txt”,”r”)
f1.close()
str=“ “
Example 9: Reading a complete file in a list While str:
str=f1.readline()
f1=open(“LICENSE.txt”,”r”)
print(str,end=‘ ‘)
r1=f1.readlines()
f1.close()
print(r1)
f1.close()
Activity 1 : Write python code to create a text file “test.txt” and enter 5 lines of text
into that file and display content of the file “test.txt”

Activity 2: Reading a file’s first 30 bytes and print it

Activity 3: Reading n bytes and then reading some more bytes from the last position
read
File Access Modes:
TEXT BINARY FILE DESCRIPTION NOTES
FILE MODE
MODE
‘r’ ‘rb’ Read only File must exist already, otherwise I/O error will raise
‘w’ ‘wb’ Write only If the file does not exist, file is created.
If the file exists, python will truncate existing data over write in
the file

‘a’ ‘ab’ Append File is in write only mode.


IF the file exists, the data in the file is retained and new data
being written will be append to the end.
If the file does not exists, python will create a new file

‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised, both reading and
writing operations can take place

‘w+’ ‘w+b’ or ‘wb+’ Write and read File is created if does not exists
If the file exists, file is truncated ( past data is lost)
Both reading and writing operations can take place

‘a+’ ‘a+b’ or ‘ab+’ Write and read File is created if does not exists
If file exists, file’s existing data is retained, new data is
appended
def write(): Activity 1
f=open(r"C:\Users\IT Dpet\Desktop\FirstFile.txt","w")
for i in range(5):
n=input("enter a name\n")
f.write(n+'\n')
f.close()
def read():
f=open(r"C:\Users\IT Dpet\Desktop\FirstFile.txt","r")
for i in f:
print(i.strip())
f.close()
#write()
read()
def noc():
f=open(r"C:\Users\Admin\Desktop\test.txt","r")
f1=f.read()
print(len(f1))
f.close() Counting
def now(): number of
f=open(r"C:\Users\Admin\Desktop\test.txt","r") characters and
count=0 numbers of
for i in f: Words in a File
word=i.split()
print(word)
count=count+len(word)
print(count)
f.close()
noc()
now()
Example :
1. Write a program to display the size of the file in bytes
2. Write a program to print number of lines in the file
3. Display the size of a file after removing EOL characters,
leading and trailing white spaces and blank lines
Example : Write a program to display the size of the file in
bytes

f1=open(“LICENSE.txt”,”r”)
r1=f1.read()
size=len(r1)
Print(size,”bytes”) Example : Write a program to print number of lines
in the file

f1=open(“LICENSE.txt”,”r”)
r1=f1.readlines()
linec=len(r1)
Print(linec)
example: display the size of a file after removing EOL characters, leading and
trailing white spaces and blank lines.
myfile=open(“license.txt”,”r”)
str1=“ “
size=0
size1=0
while str1:
str1=myfile.readline()
size1=size1+len(str1)
size=size+len(str1.strip())
print(“size of file after removing all EOL characters & blank lines:”, size)
print(“ total size of the file “, size1)
myfile.close()
Note:

strip() function is used to remove trailing and

leading whitespaces.

rstrip() : removes given character from trailing

end i.e, right end


Writing onto Files:

NAME SYNTAX DESCRIPTION


write() <filehandle>.write(str) writes string str to
filehandle
writelines() <filehandle>writelines(str) writes all strings in llist as
lines to filehandle
In python, writing in files can take place in following forms:

1. In an existing file, while retaining its content

a. if the file has been opened in append mode to retain old content

b. If the file has been opened in ‘r+’ or ‘a+’ modes to facilitate reading as well as writing

2. To create a new file or to write on an existing file after truncating/overwriting its old content

a. if the file has been opened in write-only mode (“w”)

b. if the file has been open in ‘w+’ mode to facilitate writing as well as reading
Activity:

1. Create a file to hold some data, separated as lines

2. Create a file with some names separated by newline


characters without using write() function.
f=open(r"C:\Users\AKSHARA\Desktop\

Test.txt","w")

x=1

while x==1:

d=input("enter text data")

f.write(d+'\n')

x=int(input("enter 1 to continue or other

number to exit"))

f.close()
f=open(r"C:\Users\AKSHARA\Desktop\
Test.txt","w")
x=1
while x==1:
l=[]
rn=int(input("enter rollno"))
l.append(rn)
name=input("enter your name")
l.append(name)
f.writelines(str(l))
x=int(input("enter 1 to continue or other
number to exit"))
f.close()
1. Write a python program to read a file “ data.txt” and display
those lines whose length is more than 45 characters

f=open(r'C:\Users\Admin\Desktop\myfile.txt','r')
for i in f:
if len(i)>45:
print(i.strip())
Write a program to count number of lines which all are starting with
‘A’ or ‘a’

count = 0
f=open('license.txt','r')
for i in f:
if i.startswith('A') or i.startswith('a'):
count += 1
print(count)
1. Write a method in python to read content from a text file line by
line and display the same on the screen
# Open the file in read mode
f=open(r'license.txt', 'r')
# Read all lines from the file into a list
lines = f.readlines()
# Display each line
for line in lines:
print(line.strip())# Remove any trailing newline characters
1. Write a program to read lines from a text file and display the
lines which all are starting with an alphabet ‘A’

f=open('license.txt','r')
f1 = f.readlines()
for i in f1:
if i.startswith('A'):
print(i.strip())
Write a python program to replace the word by another word in a given file.

f=open(r'C:\Users\Admin\Desktop\myfile.txt','r')
content = f.read()
# Replace the old word with the new word
content = content.replace('first', 'ffiirrsstt')
f.close()
# Write the updated content back to the file
f1=open(r'C:\Users\Admin\Desktop\myfile.txt', 'w')
f1.write(content)
f1.close()
✔ Write a program that reads a text file and create another file that is identical except that every sequence of
consecutive white spaces is replaced by a single space
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")
f2=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","w")
s=" "
while s:
s=f1.readline()
s1=s.split()
print(s1)
for i in s1:
f2.write(i)
f2.write(" ")
f2.write("\n")
f1.close()
f2.close()
wap to count no.of uppercase character in a file

f=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")

count=0

s=f.read()

for i in s:

if i.isupper():

count+=1

print("no of uppercase letters are",count)


✔ Write a program to count no.of ‘to’ or ‘the’ in a file.
✔ Note: ignore case

f1=open('C:\\Users\\AKSHARA\\Desktop\\Test1.txt','r')
s=" "
count=0
while s:
s=f1.readline()
s1=s.split()
for i in s1:
i=i.lower()
if i=='to' or i=='the' or i=='to\n' or i=='the\n' or i=='to,' or i=='the,':
count+=1
print(count)
f1.close()
✔ Python program for counting number of lines in a text file

f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
count=0
# Reading from file
rec=f1.read()
clines= rec.split("\n")
for i in clines:
if i:
count += 1
print("number of lines in the file")
print(count)
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
s=" "
c=0
while s:
s=f1.readline()
s1=s.split(' ')
for i in s1:
✔ Python program to count no.of ‘to’ words in a file if 'to' in i.lower():
c+=1
'''i=i.lower()
if i=='to' or i=='to\n' or i=='to,':
c+=1'''
print("number of 'to' in a file",c)
f1.close()
✔ Python program to print the longest line in a file

f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
s=f1.readline()
str=s
max=len(s)
while s:
s=f1.readline()
if len(s)>max:
str=s
max=len(s)
print(str)
f1.close()
✔ WAP to print the statistics of a given file like no.of lines, no.of empty lines, average characters per line,
average characters per empty lines

f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")
str=" "
line=0
empty=0
characters=0
str=f1.readlines()
print("no.of lines in a file", len(str))
for line in str:
characters=characters+len(line)
if line=='\n':
empty+=1
print('no.of empty lines',empty)
print("avg characters per line",characters/len(str))
print("avg characters per empty line", characters//empty)
f1.close()
Flush() function:
When you want to write onto a file using any of the write function, python holds everything to write in the file in
buffer
and pushes it onto actual file on storage device a later time.
If however you want to force python to write the content of buffer onto storage, we can use flush() function.

Ex:
f=open(“sample.txt”,”w+”)
f.write(“c program”)
f.write(“c++ program”)
f.write(“java program”)
f.flush()
S=‘ok’
f.write(“python program”)
f.write(“\n”)
f.flush()
f.close()

Note:
flush() function forces the writing of data on disc still pending in output buffer
STANDARD INPUT, OUTPUT AND
ERROR STREAMS
Standard input device (stdin) 🡪 reads from the keyboard

Standard output device (stdout) 🡪 prints to display

Standard error device (stderr) 🡪 same as stdout but only

for errors
Example:

import sys
f=open("sample.txt","w")
sys.stdout.write("welcome")
DIVISION OF TWO NUMBERS
import sys
sys.stdout.write("enter first number")
a=int(sys.stdin.readline())

sys.stdout.write("enter second number")


b=int(sys.stdin.readline())

if b==0:
sys.stderr.write("cannot divide")
else:
sys.stdout.write("division possible")
print(a/b)
Reading data from the file with stdin, stdout, stderr

import sys
sys.stdout.write("enter file name")
file=sys.stdin.readline()
f=open(r"C:\Users\Admin\Desktop\myfile.txt","r")
while True:
ch=f.read(1)
if ch=='':
sys.stderr.write("End of File")
break
else:
print(ch,end='')
f.close()
Sample code:
import sys
f=open("sample.txt","r+")
x=f.readline()
sys.stdout.write("python")
m=sys.stdin.read()
f.write(m)
n=sys.stdin.readline()
f.write(n)
sys.stderr.write(“error , file not closed")
import sys

f=open("check.txt","r+")

x=f.readline()

sys.stdout.write("name: "+x)

m=sys.stdin.read()

sys.stdout.write(m)

y=sys.stdin.readline()

sys.stdout.write(y)

sys.stderr.write("no error in the program")

f.close()
import sys
f=open("check.txt","r+")
z=1
while z==1:
x=f.readline()
sys.stdout.write("name: "+x)
m=sys.stdin.read()
sys.stdout.write(m)
y=sys.stdin.readline()
sys.stdout.write(y)
z=input("press 1 to continue or other
number to exit")
sys.stderr.write("no error in the
program")
File Pointer and read function:

f=open(“file.txt”,”r”)
print(f.read(2))
print(f.read(3))
Open a file Using with:

with open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r") as f:
x=f.read(2)
print(x)

• Note: with function will close the file automatically. No need to


use close()
Binary files
A binary file is a file stored in binary format.
A binary file is computer readable format file.
All executable programs are stored in binary file

Note:
Open() function is used to open binary file
Eg: f=open(“sample.dat”, “rb)
tell()
? This method can be used to get the position of the file handle
(Or )
? This method returns an integer giving the current position of object in the file.

? Syntax: file_object.tell()
Example:

Example 1:

f=open("sample1.txt

","r")

print(f.read(2))

print(f.tell())

print(f.read(3))

print(f.tell())
w e l c o m e t o p y t h o N
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
seek ()
? Seek function is used to change the position of the file pointer to a given specific
position
(Or )
? Seek method is used to position the file object at particular place in the file

? Syntax: fileobject.seek (offset, reference point)


offset : no.of
The reference positions
point to moveby
is selected forward
the from_what argument. It accepts
threereference
values: point: It defines points of reference

● 0: sets the reference point at the beginning of the file

● 1: sets the reference point at the current file position

● 2: sets the reference point at the end of the file


Example:

f=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt", "r")

print(f.seek(1))

print(f.read(2))

print(f.tell())

print(f.seek(1))

print(f.read(2))

print(f.tell())
f = open("abc.txt", "r")
f.seek(15)
print("Cursor Position :",f.tell())
data = f.read()
print(data)

f = open("abc.txt", "rb")
f.seek(-10, 2)
print("Cursor Position :",f.tell())
data = f.read()
print(data)
f=open(r"C:\Users\Admin\Desktop\myfile.txt","rb")
print(f.read(1))
print(f.tell())
f.seek(-1,2)
print(f.read())
With statement
? With statement in python is used in exception handling to make the
code cleaner and much more readable.
? With statement implicitly closes the file and even if exception is
generated, it preserves the content of the file

? Syntax:
with open(‘path’,’mode’) as <file_handle>:
? Example:
with open(“sample.tx”,”w”) as f:
f.write()
Binary files: pickling and unpickling

? Pickling refers to the process of converting structure into byte stream


before writing to the file

Structure
(list, dictionary pickling Byte stream
etc)
Unpickling:

? It will converts byte stream back to the original structure

Structure
Byte stream
unpickling (list, dictionary
etc)
dump():

? Used to write the object in a file


? Syntax: pickle.dump(structure, fileobject)
load():

? Used to read the data from the file


? Syntax; structure= pickle.load(fileobject)
Example: dump()
import pickle
f=open("binarywrite.dat","wb")
list=['c','c++','java','python']
pickle.dump(list,f)
print("sucess")
f.close()
Example: load()

import pickle

f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\binarywrite.dat","rb")

lst=pickle.load(f)

print(lst)
(or)
f.close() f=open("test1.dat","

rb")

pickle.load(f)

print(l)
import pickle
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","wb")
l=[]
ch='y'
while ch=='y':
name=input("enter ur name")
rno=int(input("enter rollno")) load, dump
l.append([name,rno]) program
ch=input("do u want to continue: 'y', 'n' ")
pickle.dump(l,f1)
print("content added successfully")
f1.close()
✔ Write a program to display all the records in a file along with line/record number.

f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.dat","rb")
count=0
rec=" "
while True:
rec=f1.readline()
if rec==" ":
break
count=count+1
print(count,rec,end=' ')
f1.close()
Try Except in Python:

import pickle
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb")
num=[5,10,15,20,25]
num1=[15,20,40,60,90]
dict={1:'Pythn', 2: 'C++'}
pickle.dump(num,f)
pickle.dump(num1,f)
pickle.dump(dict,f)
f.close()

f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
try:
while True:
s=pickle.load(f)
print(s)
except EOFError:
print("End of File Reached")
f.close()
try:
try:
x=3+3
x=3+3
except:
except:
print("they did't add due to x
x=4+4
value",x)
finally:
else:
print("will print",x)
print("will produce output with
the x value",x)

try:
x=3+3
except:
try:
x=4+4
x=x+3
else:
except:
x=x+1
x=4+4
finally:
finally:
print("will print",x)
print("will print",x)
Program for write and read in a binary file
import pickle
def write():
f=open("Test1.dat","wb") def read():
l=[] f=open(“Test1.dat","rb")
ch='y' try:
while ch=='y': s=pickle.load(f)
rno=int(input("enter rollno")) print(s)
name=input("enter ur name") except EOFError:
marks=int(input("enter marks")) pirnt("Error")
l.append([rno,name,marks]) f1.close()
ch=input("do you want to enter more press y or n")
pickle.dump(l,f)
f.close()
Program for Searching element in a binary file

def search():
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
key=int(input("enter your search element rno"))
s=pickle.load(f)
found=0
for i in s:
if i[0]==key:
print("element found",i)
found=1
if found==0:
print("no record found")
f.close()

write()
read()
search()
Program for append data in a binary file

def app():
print("want to append data")
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
l=[]
ch='y'
while ch=='y':
rno=int(input("enter rollno"))
def read():
name=input("enter ur name") f=open("Test1.dat","rb")
while True:
marks=int(input("enter marks"))
try:
l.append([rno,name,marks]) s=pickle.load(f)
for i in s:
ch=input("do you want to enter more press y or n")
print(i)
pickle.dump(l,f) except EOFError:
print("Error")
f.close()
break
f.close()
Program for update record in a binary file

def update():
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb+")
s=pickle.load(f)
rno=int(input("enter rollnumber for update record"))
found=0
for i in s:
if rno==i[0]:
print("current rno is",i[0])
i[0]=int(input("enter new number"))
found=1
break
if found==0:
print("record not found")
else:
f.seek(0)
pickle.dump(s,f)
f.close()
Program for delete record from a binary file
def Del():
f=open("Test1.dat","rb+")
s=pickle.load(f)
t=[]
found=0
a=int(input("enter the rno to be deleted"))
for i in s:
if i[0]==a:
Method - 1
found=1
else:
t.append(i)
if found==0:
print("record not found")
else:
f.seek(0)
pickle.dump(t,f)
f.close()
Program for delete record from a binary file

rno=int(input("enter roll number to be deleted"))


f=open("Test1.dat","rb")
f1=open("MyTest.dat","wb")

try:
while True:
s=pickle.load(f)
if s[0]!=rno: Method - 2
pickle.dump(s,f1)
except:
f1.close()
f.close()

os.remove(Test1.dat")
os.rename("MyTest.dat",“Test1.dat")
import pickle
ch='y'
while ch=='y':
l=[]
rno=int(input("enter rollno"))
try:
exists=0
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","wb+")
while True:
s=pickle.load(f)
if s[0]==rno:
print("rollno already exists")
Program for accepting
exists=1
break unique data from user
except EOFError: in a binary file
f.close()
if exists==0:
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
l.append(rno)
name=input("enter ur name")
l.append(name)
marks=int(input("enter marks"))
l.append(marks)
pickle.dump(l,f)
ch=input("enter y to continue")
f.close()
import pickle
#f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
l=[]
'''
ch='y'
l.append([rollno,name])
while ch=='y':
ch=input("do you want to continue
rollno=int(input("enter your rollno"))
press y or N")
name=input("enter your name")
pickle.dump(l,f)
try:
f.close()
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
check=0
f=open("C:\\Users\\AKSHARA\\
while True:
Desktop\\Python Programs\\
s=pickle.load(f)
Test1.dat","rb")
if s[0]==rollno:
try:
print("already exists")
while True:
check=1
s=pickle.load(f)
break
print(s)
except EOFError:
except EOFError:
f.close()
print("EOF")
if check==0:
f.close()'''
l.append(rollno)
l.append(name)
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
pickle.dump(l,f)
ch=input("enter y to continue")
f.close()
import pickle name=input("enter ur name")
def search(): rno=int(input("enter rollno"))
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb") l.append([name,rno])
a=int(input("enter search no")) #pickle.dump(l,f1)
found=0 ch=input("do u want to continue: 'y', 'n' ")
try: pickle.dump(l,f1)
while True and found==0: print("content added successfully")
r=pickle.load(f1) f1.close()
if r[0]==a:
print("found") def read():
print(r) f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
found=1 try:
except EOFError: while True:
print("end of file reached") l=pickle.load(f1)
f1.close() print(l)
def write(): except EOFError:
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb") f1.close()
l=[]
ch='y' write()
while ch=='y': read()
search()
read()
import pickle
ch='y'
if exists==0:
while ch=='y':
l.append(roll)
l=[]
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb")
roll=int(input("enter rollno"))
name=input("enter your name")
try:
l.append(name)
exists=0
marks=[]
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
for i in range(0,3):
while True:
x=float(input("enter marks"))
s=pickle.load(f)
marks.append(x)
if s[0]==roll:
l.append(marks)
print("roll number exists")
pickle.dump(l,f)
exists=1
ans=input("enter y to continue")
break
f.close()
except EOFError:
f.close()
Python - OS
Module

The OS module in Python provides functions for creating and removing a directory (folder),
fetching its contents, changing and identifying the current directory, etc.

Getting Current Working


Directory
>>> import os
>>>
os.getcwd()
Creating a
Directory
>>> import os
>>> os.mkdir(“c:\
Pythonfolder”)
import pickle
import os

def add_record():
try:#function definition

if os.path.isfile("stud"):
f=open("stud","ab")
else:
f=open("stud","wb")
roll=int(input("Enter roll no "))
name=input("Enter name ")
name=name.upper()
per=float(input("Enter per "))
rec=[roll,name,per]
pickle.dump(rec,f)
print("Record added in file")
except EOFError:
f.close()
add_record()
COMMA SEPARATED VALUES

CSV FILES
⮚ To share large amount of data through spreadsheets or

databases, basic approach is CSV file.

⮚ CSV file is a simple flat file in a human readable format which

is extensively used to store data, in a spreadsheet or

database.

⮚ A CSV file stores tabular data (numbers and text) in plain text

For working with CSV files in Python, there is an inbuilt module called
CSV. It is used to read and write tabular data in CSV format.
Features:

• Files in CSV format can be imported and exported


• Comma separated file is a delimited text file that uses a comma to
separate values.
Advantages

• Faster to handle
• Smaller in size
• Easy to generate and import onto a spreadsheet or database
• Human readable and easy to edit
• Simple to implement
Python CSV modules

csv modules provides two types of objects:

• Reader : to read from csv file

• Writer: to write in to the csv file

there are two basic operations that can be carried


out on a CSV file:
1.Reading from a CSV file
2.2. Writing to a CSV file
Open a csv file:

f=open(“student.csv”,”w”)
(or)
f= open(“student.csv”,”r”)
Functions used to write csv file:

• writerow(): it is used to write one record at a time


syntax: writerobject.writerow(data)

writerows(): it is used to write multiple rows


syntax: writerobject.writerows(data)
Example : writerow( )

import csv
fields =['rno', 'name', 'classes', 'section']
rows=[['1','raj','12','A'],
['2', 'ram', '12', 'B']]
with open("std.csv",'w') as f1:
w=csv.writer(f1)
w.writerow(fields)
for i in rows:
w.writerow(i)
Writerows( ):

import csv
fields =['rno', 'name', 'classes', 'section']
rows=[['1','raj','12','A'],
['2', 'ram', '12', 'B']]
with open("std.csv",'w') as f1:
w=csv.writer(f1)
w.writerow(fields)
w.writerows(rows)
import csv
def write(): def read():
f=open(“mycsvfile.csv","w",newline='') f=open(“mycsvfile.csv","r")
w=csv.writer(f,delimiter='\t') r=csv.reader(f)
w.writerow(['RollNo','Name','Marks','Class']) for i in r:
while True: print(i)
r=int(input("rollno")) write()
n=input("enter name") read()
m=int(input("marks"))
c=input("enter class")
data=[r,n,m,c]
w.writerow(data)
ch=input("press Y to continue")
if ch in 'Nn':
break
f.close()
import csv
fields =['rno', 'name', 'classes', 'section']
rows=[]
ch='y'
while ch=='y':
name=input("enter your name")
rno=input("enter your rollno")
Class=input("enter your class")
section=input("enter your section")
rec=[name,rno,Class,section]
rows.append(rec)
ch=input("do you want to add more records y/N")

Standard with open("std.csv",'w',newline='') as f1:


w=csv.writer(f1)

input: w.writerow(fields)
w.writerows(rows)
Read from CSV file:

• To read from CSV file we have to open file in “r” mode and create a
folder object for the file

• Syntax: reader object name=csv.reader(filehandler)


Read data from csv file:

import csv
with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
for i in r:
print(i)
print()
import csv
field=[]
row=[]
with open("std.csv","r",newline='\
r\n')as f:
r=csv.reader(f)
field=next(r)
for i in field:
print(i,end='\t')
print()

for row in r:
for i in row:
print(i)
print()
import csv

with open("std.csv","w") as f:
w=csv.writer(f)
w.writerow(['SNO','SNAME','SADD'])
ch='y'
while ch=='y':
sno=int(input("enter rno"))
sname=input('enter name')
sadd=input("enter address")
w.writerow([sno,sname,sadd])
ch=input("enter ur choice")
print("data added successfully")

with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
data=list(r)
for row in data:
for column in row:
print(column,'\t',end='')
print()
# Program for printing number of records

with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
c=0
data=list(r)
for row in data:
c+=1
print(c-1)
# Program for printing number of records
import csv
def read():
with open("C:\\Users\\AKSHARA\\Desktop\\
Python Programs\\std.csv",'r') as f1:
row=csv.reader(f1)
c=0
for i in row:
c=c+1
print("no.of records are",c)
read()
# Program for printing number of records -
method 2
import csv
def read():
with open("C:\\Users\\AKSHARA\\Desktop\\
Python Programs\\std.csv",'r') as f1:
row=csv.reader(f1)
c=0
for i in row:
print(i)
print()
print("no.of records ",row.line_num)
Program to print the records in the form of comma separated
values, instead of lists.

with open("std.csv","r",newline='\
r\n') as f:
r=csv.reader(f)
c=0
data=list(r)
for row in data:
print(','.join(row))
# Program to search the record of a particular student
from CSV file on the basis of input name.

import csv
f=open(“std.csv”,”r”)
r=csv.reader(f)
name=input(“enter name to be searched”)
for row in r:
if row[0]==name:
print(row)
Practice Programs
Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the lines which are not starting with any
vowel.

def COUNTLINES() :

file = open ('TESTFILE.TXT', 'r')

lines = file.readlines()

count=0

for w in lines :

if (w[0]).lower() not in 'aeoiu'

count = count + 1

print ("The number of lines not starting with any vowel: ",
count)

file.close()
Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT” and then
count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).

def ETCount() :

file = open ('TESTFILE.TXT', 'r')

lines = file.readlines()

countE=0

countT=0

for w in lines :

for ch in w:

if ch in 'Ee':

countE = countE + 1

if ch in 'Tt':

countT=countT + 1

print ("The number of E or e : ", countE)

print ("The number of T or t : ", countT)

file.close()
Rohit, a student of class 12th, is learning CSV File Module in Python.
During examination, he has been assigned an incomplete python code
(shown below) to create a CSV File 'Student.csv' (content shown below).
Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
import_____ #Statement-1

fh = open(_____, _____, newline='') #Statement-2

stuwriter = csv._____ #Statement-3

data = []

header = ['ROLL_NO', 'NAME', 'CLASS', 'SECTION']

data.append(header)

for i in range(5):

roll_no = int(input("Enter Roll Number : "))

name = input("Enter Name : ")

Class = input("Enter Class : ")

section = input("Enter Section : ")

rec = [_____] #Statement-4

data.append(rec)

stuwriter. _____ (data) #Statement-5

fh.close()
Amritya Seth is a programmer, who has recently been given a task to write a python code to
perform the following binary file operations with the help of two user defined
functions/modules: a. AddStudents() to create a binary file called STUDENT.DAT containing
student information – roll number, name and marks (out of 100) of each student. b.
GetStudents() to display the name and percentage of those students who have a percentage
greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent. He has
succeeded in writing partial code and has missed out certain statements, so he has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Amritya.

You might also like