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

Filehandling Prog

File handling

Uploaded by

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

Filehandling Prog

File handling

Uploaded by

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

# 1.

reading files entire content


f1=open("poem.txt","r")
st1=f1.read()
print(st1)
print("size of a file", len(st1))
f1.close()
# 2. reading a file using for loop
f1=open("poem.txt","r")
for line in f1:
print(line)
f1.close()
# 3.reading a file line by line
f1=open("poem.txt","r")
st1=f1.readline()
print(st1)
st1=f1.readline()
print(st1,end="")
st1=f1.readline()
print(st1)
f1.close()
# 4. reading a file line by line using while loop
f1=open("poem.txt","r")
str=" "
while str:
st1=f1.readline()
print(st1,end="")
f1.close()
# 5.program to read complete file in a list
f1=open("poem.txt","r")
st1=f1.readlines()
print(st1)
print("no.of lines",len(st1))
f1.close()
# 6. program to write data in a file
f1=open("stu.txt","w")
for i in range(5):
name =input("enter name")
mark =int(input("enter mark"))
rec= name+'\t'+str(mark)+'\n'
f1.write(rec)
f1.close()
#7. program to write date using writelines
f1=open("stu.txt","w")
list1=[]
for i in range(5):
name =input("enter name")
mark =int(input("enter mark"))
rec= name+'\t'+str(mark)+'\n'
list1.append(rec)
f1.writelines(list1)
f1.close()
#8. program to read text file , seperate each word by #
f1=open("stu.txt","r")
line=" "
while line:
line=f1.readline()
word=line.split()
for w in word:
print(w,end='#')
print()
f1.close()
#9. count no of vowels and consonents in the file
f1=open("stu.txt","r")
ch=" "
v=0
c=0
while ch:
ch=f1.read(1)
if ch in ['a','e','i','o','u','A','E','I','O','U']:
v+=1
else:
c+=1
print("no of vowels:",v)
print("no of consonents:", c)
f1.close()
#10.program to count number of me and my in a text file.
num=0
f=open("stu.txt")
n=f.read()
s=n.split()
for i in s:
if i=='me' or i=='my':
num+=1
print("no of me and my:", num)
f.close()
● A text file is structured as a sequence of lines.
● Line is a sequence of characters (ASCII or UNICODE)
● Stores information in ASCII or Unicode characters.
● Each line of text is terminated by a special character known as End Of
Line character.
● Text files are stored in human readable form and they can also be
created using any text editor.
● Stored with the extension of .txt
● <file_object_name> = open(<file_name>,<mode>)
● f = open(“demo.txt”,”r”), f.close()

● Mode ● Description ●

● “r” ● Read ● Default value. Opens a file for reading,


error if the file does not exist.

● “w” ● Write ● Opens a file for writing, creates the file if it


does not exist

● “a” ● Append ● Opens a file for appending, creates the file


if it does not exist

● “r+” ● Read and ● File must exist otherwise error is


Write raised.Both reading and writing operations
can take place.

● “w+” ● Write and ● File is created if it does not exist.If the file
Read exists past data is lost (truncated).Both
reading and writing operations can take
place.

● “a+” ● Append ● File is created if it does not exist.If the file


and Read exists past data is not lost .Both reading
and writing(appending) operations can
take place.
Binary files:
#1.program to write and read binary file.
import pickle
f1=open("ff.dat","wb")
stu="Jaikrishnan"
pickle.dump(stu,f1)
f1.close()
f1=open("ff.dat","rb")
a=pickle.load(f1)
print(a)
f1.close()
#2. program to get student no,name,marks and write in file and display it.
import pickle
stu={}
f1=open("ff.dat","wb")
ans='y'
while ans=='y':
rno=int(input("enter no:"))
name=input("enter name:")
mark=float(input("enter marks:"))
stu['rno']=rno
stu['name']=name
stu['mark']=mark
pickle.dump(stu,f1)
ans=input("want to continue:y/n:")
f1.close()
f1=open("ff.dat","rb")
stu1={}
try:
while True:
stu1=pickle.load(f1)
print(stu1)
except:
f1.close()
#3. program to search rno and display
import pickle
with open("ff.dat","rb")as f1:
stu1={}
found=False
try:
while True:
stu1=pickle.load(f1)
if stu1['rno']in [1,2,3]:
print(stu1)
found=True
except:
if found==False:
print("no data found")
f1.close()
#4.program to search marks>81 and display
import pickle
with open("ff.dat","rb")as f1:
stu1={}
found=False
try:
while True:
stu1=pickle.load(f1)
if stu1['mark']>81:
print(stu1)
found=True
except:
if found==False:
print("no data found")
f1.close()
#5.program to search marks>81 and display
import pickle
with open("ff.dat","rb+")as f1:
stu={}
found=False
try:
while True:
rpos=f1.tell()
stu=pickle.load(f1)
if stu['mark']>81:
stu['mark']+=2
f1.seek(rpos)
pickle.dump(stu,f1)
found=True
except:
if found==False:
print("no data found")
else:
print("updated successfully")
f1.close()
● Files that store objects as byte stream are called binary files.
● That is, all the binary files are encoded in binary format , as a sequence of bytes,
which is understood by a computer or machine.
● In binary files, there is no delimiter to end the line.
● Since they are directly in the form of binary, there is no need to translate them.
● But they are not in human readable form and hence difficult to understand
● Uses pickle module
● pickle.dump(<structure>,<FileObject>), <structure> = pickle.load(<FileObject>)


Mode Description

“rb” Read Default value. Opens a file for reading, error if the file does
not exist.

“wb” Write Opens a file for writing, creates the file if it does not exist

“ab” Append Opens a file for appending, creates the file if it does not exist

“r+b”or Read and File must exist otherwise error is raised.Both reading and
Write writing operations can take place.
“rb+”

“w+b”or Write and File is created if it does not exist.If the file exists past data is
Read lost (truncated).Both reading and writing operations can
“wb+”
take place.

“a+b” or Append File is created if it does not exist.If the file exists past data is
and Read not lost .Both reading and writing operations can take place.
“ab+”

Random Access in Files : tell() and seek()

❏ tell() function is used to obtain the current position of the file pointer
Syntax : f.tell()

❏ File pointer is like a cursor, which determines from where data has to be
read or written in the file.

❏ seek () function is used to change the position of the file pointer to a


given position.
Syntax : f.seek(offset,reference_point)
Where f is the file object
CSV FILES:
● CSV stands for Comma Separated Values.It is a type of plain text file that
uses specific structuring to arrange tabular data such as a spreadsheet or
database.
● CSV like a text file , is in a human readable format and extensively used
to store tabular data, in a spreadsheet or database.
● Each line of the file is a data record.
● Each record consists of one or more fields, separated by commas.
● The separator character of CSV files is called a delimiter.
● Default delimiter is (,).
● Other delimiters are tab(\t), colon (:), pipe(|), semicolon (;) characters.
● csv.writer() :Returns a writer object which writes data into csv files.
● writerow() :Writes one row of data onto the writer object.
Syntax : <writer_object>.writerow()
● writerows() : Writes multiple rows into the writer object
Syntax : <writer_object>.writerow()
Create the reader object. demo_reader = csv.reader(f)
3. program to write the students data in the file
import csv
f=open("rt.csv","w", newline="")
a=csv.writer(f)
a.writerow(["name","rollno","marks"])
x="y"
l1=[]
while x=="y":
name=input("enter name")
rno=int(input("enter roll no :"))
mark=int(input("enter marks:"))
x=input("do you want to enter more :(y/n):")
l1=[name,rno,mark]
a.writerow(l1)
f.close()
4. program to search and display whose mark is greater than 80.
import csv
f12=open("rt.csv","r")
ab=csv.reader(f12)
for i in ab:
if i[2]>=80:
print(i)
f12.close()
5.program to search and display who got more than 80 and also display the
count.
import csv
f12=open("rt.csv","r")
count=0
ab=csv.reader(f12)
for i in ab:
if i[2]>=80:
print(i)
count+=1
print("no of student got more than 80:",count)
f12.close()
The flush() function():
The flush() function forces the writing of data on disc still pending in output
buffer. Flush() function should write after the write method in the
program.
Eg:
F1.write(“xyz”)
F1.flush()
File modes and the opening position of file pointer:
File modes Opening position of the file pointer
r,rb,r+,rb+,r+b Beginning of the file
w,wb,w+,wb+,w+b Beginning of the file
a,ab,a+,ab+,a+b End of the file

Standard Input, output and Error Streams:


Standard input device(stdin) – read from the keyboard
Standard output device(stdout) – display using monitor
Standard error device(stderr) – monitor is a error device
import sys module to stdin, stdout and stderr functions.
Eg: sys.stdout.write(l1)

You might also like