TEXT FILES
• A file object is also known as file handle
• file extension is .txt
• Each line is terminated by a special EOL character as per the OS
• In Python, by default, this EOL character is the newline character ('\n') or
carriage-return, newline combination ('\r\n')
• Please note that when you open a file in readmode, the given file must exist
in the folder, otherwise Python will raise FileNotFoundError
• Python's open() function creates a file object which serves as a link to a file
residing on your computer
• The first parameter for the open() function is a path to the file you'd like
to open. If just the file name is given, then Python searches for the file in
the current folder.
• The second parameter of the open function corresponds to a mode which is
typically read ('r'), write ('w'), or append ('a') If no second parameter is
given, then by default it opens it in read (r) mode.
• The prefix r in front of a string makes it raw string that means there is no
special meaning attached to any character.
f = open("c:\\temp\\data.txt", 'r')
f = open(r "c:\temp\data.txt", "r")
• To create a file, you need to open a file in a mode that supports write mode
(ie., 'w', or 'a' or 'w+' or 'a+' modes).
• A close() function breaks the link of file-object and the file on the disk.
After close(), no tasks can be performed on that file through the file-
object (or file-handle).
<filehandle>.close()
read() , readline(), readlines()
read (): Returns the read bytes in the form of a string. Reads n bytes; if n is not
specified, then reads the entire file.
readline (): Reads a line of the file and returns in the form of a string. For
specified n, reads at most n bytes. readline () function does not read more than
one line at a time; even if n exceeds, it reads only one line. Readline () function
reads a line of the file and returns it in the form of a string. It takes an integer
value n as a parameter to read the number of characters read at a time. Also, if
the end of the file is reached, it will return an empty string.
readlines (): Reads all the lines and returns them as a string element in a list.
• read() method returns an empty string when all the contents are read
• readline() reads a line of text followed by a new line character returns an
empty string when no lines are to be read
• readlines() returns an empty list when no content to be read
write() and writelines()
The write() function will write the content in the file without adding any extra
characters.
Syntax:
# Writes string content referenced by file object.
file_name.write(content)
As per the syntax, the string that is passed to the write() function is
written into the opened file. The string may include numbers, special
characters, or symbols. While writing data to a file, we must know that the
write function does not add a newline character(\n) to the end of the string.
# write all the strings present in the list "list_of_lines"
# referenced by file object.
file_name.writelines(list_of_lines)
the list of strings that is passed to the writelines() function is written into
the opened file. Similar to the write() function, the writelines() function
does not add a newline character(\n) to the end of the string.
The only difference between the write() and writelines() is that write() is used to
write a string to an already opened file while writelines() method is used to write
a list of strings in an opened file.
Example:
f=open("pythonwrite.txt",'w+')
f.write("WE LEARN PYTHON\n")
L=["WE LEARN JAVA\n","WE LEARN DBMS\n"]
f.writelines(L)
f.seek(0)
s=f.read()
print(s)
f.close()
Two methods to open a File.
✓ Using open () function ✓ Using with statement
Benefits of using with statement:
This method is very handy when you have two related operations which you would
like to execute as a pair, with a block of code in between.
It automatically closes the file after the nested block of code.
It also handles all the exceptions also occurred before the end of block.
Example: with open ("Output.txt","w") as f:
f.write ("Text")
Differentiate between r+, w+ ,a+ file modes in Python.
r+ mode(read and write)
Primary function is reading
File pointer is at beginning of file
if the file does not exist, it results in an error
w+ mode: (write and read)
primary function is writing
if the file does not exist, it creates a new file.
If the file exists, previous data is overwritten
File pointer is at the beginning of file
a+ mode: (write and read)
primary function is writing
File is created if does not exist.
If file exists, file's existing data is retained; new data is appended.
Both reading and writing operations can take place.
File pointer will be at the end of the file.
PROGRAMS
1. PROGRAM TO COUNT THE WORDS THAT BEGIN WITH A AND BEGIN
WITH U
def VOWEL_WORDS():
f=open("train.txt",'r') # we opening the file in read mode
str=f.read() #read() will return a string
v=u=0
L=str.split() # will create a list default spilt character is whitespace
for i in L:
if(i[0] in "Aa"):
v=v+1
if(i[0] in 'Uu'):
u=u+1
print("words that begin with the letter a ",v);
print("words that begin with the letter u ",u)
VOWEL_WORDS()
2. PRINT THE LINES THAT DOES NOT CONTAIN ke
def SHOWLINES():
f=open("TESTFILE.txt",'r')
str=f.readlines() #returns a list
print(str)
for i in str:
if 'ke' not in i:
print(i,end='')
f.close()
SHOWLINES()
3. WRITING THE DICTIONARY AND TUPLES INTO TEXT FILES
f=open("newfile1.txt",'w')
dic={'1':'RRRR','2':'GGGG'}
tup=('\n aaaa','\n bbbb')
for i in dic.values():
f.write(i)
f.writelines(tup)
f.close()
4. APPENDING
f=open("PROG.txt",'a+')
f.write('\n LEARNING TODAY')
f.seek(0)
s=f.read()
print(s)
f.close()
5. SEEK METHOD
f=open(r"C:\Users\meena\OneDrive\Desktop\FILES\PYTHON1.txt",'w+')
f.write('ABC')
f.seek(0)
str=f.read()
print(str)
f.close()
6. SEEK
f=open("PYTHON.txt",'rb')
str=f.read(4)
print(str)
str=f.read(40)
print(str)
f.seek(2,0)
str=f.read(2)
print(str)
f.seek(5,1)
str=f.read()
print(str)
f.seek(1)
str=f.read()
print(str)
f.seek(-5,2)
str=f.read()
print(str)
7. COUNT IS AND FOR IN THE FILE
def countwords():
f=open(r"C:\Users\meena\OneDrive\Desktop\FILES\SAMPLE.txt",'r')
str=f.read()
c=0
words=str.split()
print(words)
for i in words:
if(i=='is' or i=='for'):
c+=1
print("The frequency of the word 'is'or ‘for’ :",c)
f.close()
countwords()
8. SEEK AND TELL
def reading():
f=open(r"C:\Users\meena\OneDrive\Desktop\FILES\SAMPLE_TEXT.txt",'rb')
print(f.tell())
f.seek(10,0)
m=f.read(3)
print(m)
print(f.tell())
f.seek(-5,2)
m=f.read()
print(m)
f.seek(5)
print(f.read())
reading()
9. WRITELINES
def reading():
f=open("shanu.txt",'w+')
f.writelines("\n call by reference")
f.writelines("\n call by value")
f.seek(0)
m=f.read()
print(m)
L=['54\n','mnc\n']
f.writelines(L)
f.seek(0)
m=f.read()
print(m)
reading()
10. SEEK AND READ
def reading():
f=open("PROG.txt",'r+')
st=f.read()
print(st)
f.write('\nPYTHON IS AN INTERPRETED LANGUAGE')
f.seek(0)
st=f.read()
print(st)
reading()
TEXT FILES
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\sample.txt",'r')
str=f.read()
print(str)
f.close()
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read(10)
print(str)
f.close()
PRINT ONLY THOSE LINES THAT BEGINS WITH ‘W’ or ‘w’
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f. readlines()
for i in str:
if i[0]=='W' or i[0]=='w':
print(i,end='')
f.close()
reading()
REMOVING ALL THE LINES THAT CONTAIN ‘a’ and storing in another file
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
f1=open(r"C:\Users\LENOVO\Desktop\FILES\sample2.txt",'w')
str=f.readlines()
for i in str:
if 'a' not in i:
f1.write(i)
f.close()
reading()
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
f1=open(r"C:\Users\LENOVO\Desktop\FILES\sample2.txt",'w')
str=f.readlines()
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample3.txt",'w')
for i in str:
if 'a' not in i:
f1.write(i)
else:
f.write(i)
f.close()
reading()
TO STORE THE LINES THAT DOES NOT BEGIN WITH A LOWER CASE
LETTERS IN A SEPARATE FILE
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
f1=open(r"C:\Users\LENOVO\Desktop\FILES\sample2.txt",'w')
str=f.readlines()
f2=open(r"C:\Users\LENOVO\Desktop\FILES\sample3.txt",'w')
for i in str:
if i[0].islower()==False:
f1.write(i)
else:
f2.write(i)
f1.close()
f2.close()
f.close()
reading()
PRINTING THE LINES THAT BEGIN WITH h OR H
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
count=0
str=f.readlines()
for i in str:
if i[0]=='H' or i[0]=='h':
count=count+1
f.close()
print(count)
reading()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
c=0
words=str.split()
for i in words:
c+=1
print(len(words))
print(c)
f.close()
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
c=0
words=str.split()
for i in words:
if(i=='is' or i=='for'):
c+=1
print("The frequency of the word 'is'or ‘for’ :",c)
f.close()
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
words=str.split()
for i in words:
if len(i)>=5:
print(i)
f.close()
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
c=0
words=str.split()
for i in words:
if len(i)>=5:
c+=1
print(c)
f.close()
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
words=str.split()
for i in words:
if i[0]=='s':
print(i)
f.close()
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
words=str.split()
for i in words:
if i[-1]=='s' or i[0]=='s':
print(i)
f.close()
countwords()
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
c=0
for i in str:
if i.isspace():
c+=1
print(c)
f.close()
reading()
islower()
isupper()
isdigit()
isalnum()
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
sum=0
for i in str:
if i.isdigit():
if int(i)%2==0:
sum=sum+int(i)
print(sum)
f.close()
reading()
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.readlines()
for i in str:
print(i,end='')
f.close()
reading()
readlines() functions returns a list
read() returns a string
def reading():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.readline(5)
print(str)
str=f.readline(5)
print(str)
f.close()
reading()
readline function returns string
readline(5) function returns five characters from that line
BINARY FILES
import pickle
def write():
f=open('data.dat',"wb")
list=['science','biology','physics','chemistry']
dic={'meera':1233,'sona':2321,'preethi':5656,'teddy':4943}
pickle.dump(list,f)
pickle.dump(dic,f)
f.close()
def read():
f=open('data.dat',"rb")
s=pickle.load(f)
print(s)
s=pickle.load(f)
print(s)
f.close()
write()
read()
print("data written")
import pickle
def write():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"wb")
list=['science','biology','physics','chemistry']
dic={'meera':1233,'sona':2321,'preethi':5656,'teddy':4943}
pickle.dump(list,f)
pickle.dump(dic,f)
f.close()
def read():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"rb")
s=pickle.load(f)
d=pickle.load(f)
print(s)
print(d)
f.close()
write()
read()
print("data written")
NESTED LIST PUSHED IN A BINARY FILE
def write():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"wb")
record=[]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter name:"))
age=int(input("Enter age"))
data=[rno,name,age]
record.append(data)
ch=input("do you want to continue (y/n)")
if ch=='n':
break
pickle.dump(record,f)
write()
print("records written in file")
import pickle
def write():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"wb")
record=[]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter name:")
age=int(input("Enter age"))
data=[rno,name,age]
record.append(data)
ch=input("do you want to continue (y/n)")
if ch=='n':
break
pickle.dump(record,f)
#write()
def read():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"rb")
s=pickle.load(f)
print(s)
for i in s:
print(i)
read()
print("records read from file")
def search():
found=0
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"rb")
s=pickle.load(f)
roll=int(input("enter roll number"))
for i in s:
if(i[0]==roll):
print(i)
found=1
break
if(found==0):
print("no record found")
search()
def update():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\data.dat',"rb+")
s=pickle.load(f)
found=0
rno=int(input("enter roll no"))
for i in s:
if rno==i[0]:
print("Present name is :",i[1])
i[1]=input("enter new name")
found=1
if found==0:
print("Record not found...")
else:
f.seek(0)
pickle.dump(s,f)
f.close()
update()
read()
WRITING INDIVIDUAL LIST IN A BINARY FILE
SEARCHING A ROLLNO AND PRINTING THEIR NAME
import pickle
def write():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"wb")
while True:
rno=int(input("Enter roll no:"))
name=input("Enter name:")
data=[rno,name]
pickle.dump(data,f)# 2 ARGUMENTS
ch=input("do you want to continue (y/n)")
if ch=='n':
break
write()
def read():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"rb")
try:
while True:
s=pickle.load(f)
print(s)
except EOFError:
f.close()
read()
print("records read from file")
def search():
found=0
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"rb")
rollno=int(input("enter the roll number"))
try:
while True:
s=pickle.load(f)
if s[0]==rollno:
print(s[1])
found=1
break
except EOFError:
print(“end of the file reached”)
f.close()
if(found==0):
print("no record found")
search()
UPDATE A RECORD
import pickle
def write():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"wb")
data={}
while True:
rno=int(input("Enter roll no:"))
name=input("Enter name:")
mark=int(input("Enter mark"))
data['roll']=rno
data['name']=name
data['mark']=mark
pickle.dump(data,f)# 2 ARGUMENTS
ch=input("do you want to continue (y/n)")
if ch=='n':
break
write()
def read():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"rb")
s={}
try:
while True:
s=pickle.load(f)
print(s)
except EOFError:
f.close()
read()
print("records read from file")
def update():
f=open('C:\\Users\\LENOVO\\Desktop\\FILES\\STUDENT.dat',"rb+")
found=0
try:
while True:
pos=f.tell()
stu=pickle.load(f)
if stu['mark']>90:
stu['mark']+=2
f.seek(pos)
pickle.dump(stu,f)
found=1
except EOFError:
if found==0:
print("No record found")
else:
print("Record updates sucessfully")
f.close()
update()
read()
CSV FILES[FLAT FILE OR TEXT FILE]
CSV stands for comma separated values.
It is used for storing tabular data in a spreadsheet or
database.
Each record consists of fields separated by commas(delimiter)
Each line of a file is called a record
CSV FILES are also called as flat files.
Easier to create
Preferred import and export format for databases and spreadsheets.
capable of storing large amount of data.
PYTHON CSV MODULE
csv module provides two types of objects
reader-to read from csv files
writer-to write in to csv files
import csv
newline argument specifies how would python handle new line characters while
working with csv files
on different operating systems
different operating systems store EOL characters differently
CR[\r] Carraige Return Macintosh
LF[\N] Line Feed UNIX
CR/ LF[\r\n] Carraige Return/ Line Feed MS-DOS, Windows
NULL [\0] Null Character other OS
Additional optional argument as newline='' (no space between)
with file open() will ensure the no translation of end of line (EOL) character takes
place
csc.writer() returns a writer object which writes data into csv files
writerobject.writerow() writes one row of data on to the writer object
writerobject.writerows() writes multiple rows of data on to the writer object
writerobject and reader object main purpose is users data is converted into
delimited strings
csv.reader() returns a reader object
It loads the data from CSV file into an iterable form after parsing delimited data
1. import csv module
2. open csv file in read mode
3. create the reader object
4. fetch data through for loop row by row
5. close the file
METHOD TO INSERT RECORDS IN A FILE STUDENT.CSV
import csv
def write():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","w",newline='')
wr=csv.writer(f, delimiter=’\t’)
wr.writerow(['rollno','name','marks'])
while True:
r=int(input("roll no"))
n=input("enter name")
m=int(input("enter marks"))
c=input("class :")
data=[r,n,m,c]
wr.writerow(data)
ch=input("do you want to continue")
if ch in "Nn":
break
f.close()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f,delimiter=’\t’)
for i in read:
print(i)
f.close()
write()
read()
OTHER DELIMITERS
\t, colon : , pipe | , semi colon ;
DISPLAY RECORDS OF ONLY THOSE STUDENTS WHO ARE IN CLASS XII
import csv
def write():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","w",newline='')
wr=csv.writer(f)
while True:
r=int(input("roll no"))
n=input("enter name")
m=int(input("enter marks"))
c=input("class :")
data=[r,n,m,c]
wr.writerow(data)
ch=input("do you want to continue")
if ch in "Nn":
break
f.close()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
for i in read:
print(i)
f.close()
#write()
#read()
def find():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
count=0
print(next(read))
for i in read:
if i[3]=='XII':
count+=1
print(i)
f.close()
print(count)
find()
DISPLAY ONLY THOSE WHO SECURED MORE THAN 70
import csv
def write():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","w",newline='')
wr=csv.writer(f)
wr.writerow(['rollno','name','marks',’class’])
while True:
r=int(input("roll no"))
n=input("enter name")
m=int(input("enter marks"))
c=input("class :")
data=[r,n,m,c]
wr.writerow(data)
ch=input("do you want to continue")
if ch in "Nn":
break
f.close()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
next(read)
for i in read:
if int(i[2])>=95:
print(i) # print(i[1])
f.close()
write()
read()
SEARCH A ROLLNO AND PRINT THE RECORD
import csv
def write():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","w",newline='')
wr=csv.writer(f)
wr.writerow(['rollno','name','marks',’class’])
while True:
r=int(input("roll no"))
n=input("enter name")
m=int(input("enter marks"))
c=input("class :")
data=[r,n,m,c]
wr.writerow(data)
ch=input("do you want to continue")
if ch in "Nn":
break
f.close()
roll=int(input("enter roll number"))
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
found=0
next(read)
roll=int(input(“enter the roll number”))
for i in read:
if int(i[0])==roll:
print(i)
found=1
if(found==0):
print("No .... record ..... found")
f.close()
write()
read()
CALCULATE THE SUM OF ALL MARKS GIVEN IN THE FILE
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
SUM=0
next(read)
for i in read:
SUM=SUM+int(i[2])
print(SUM)
f.close()
COPY THE DATA FROM STUDENT.CSV TO S1.CSV
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
f1=open("C:\\Users\\LENOVO\\Desktop\\FILES\\XIIrecord.csv","w",
newline='')
read=csv.reader(f)
wr=csv.writer(f1)
wr.writerow(['rollno','name','marks',’class’])
for i in read:
if i[3]=='XII':
wr.writerow(i)
f.close()
read()
def reading():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\XIIrecord.csv","r")
read=csv.reader(f)
for i in read:
print(i)
f.close()
reading()
WRITE ROWS
import csv
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\Xrecord.csv","w",newline='')
wr=csv.writer(f,delimiter=’\t’)
wr.writerow(['rollno','name','marks','class'])
rec=[]
while True:
r=int(input("roll no"))
n=input("enter name")
m=int(input("enter marks"))
c=input("class :")
data=[r,n,m,c]
rec.append(data)
ch=input("do you want to continue")
if ch in "Nn":
break
wr.writerows(rec)
f.close()
def reading():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\Xrecord.csv","r")
read=csv.reader(f)
for i in read:
print(i)
f.close()
reading()
TELL AND SEEK
0: sets the reference point at the beginning of the file
which is default
1: sets the reference point at the current file position
2: sets the reference point at the end of the file
f=open("random.txt")
print(f.tell())
f.seek(3)
print(f.read())
f.seek(6)
print(f.read(5))
print("current location of pointer=",f.tell())
f=open(r"C:\Users\LENOVO\Desktop\FILES\random.txt",'rb')
print(f.tell())
f.seek(3)
print('output ',f.read(10))
print(f.tell())
f.seek(-3,2)
print(f.read(3))
print(f.tell())
print(f.read(5))
print("current location of pointer=",f.tell())
PICKLE MODULE UPDATION
import pickle
def create():
ch='y'
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\TCH.DAT", 'wb')
while(ch=='y' or ch=='Y'):
r=int(input("Enter Teacher ID : "))
nm=input("Enter Name: ")
sj=input("Enter subject: ")
sl=int(input("Enter Salary: "))
ds=input("Enter Designation: ")
rec=[r,nm,sj,sl,ds]
pickle.dump(rec,f)
ch=input("Do you want to continue to enter records")
create()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\TCH.DAT", 'rb')
try:
while(True):
data=pickle.load(f)
print(data)
except EOFError:
print("End of the file reached")
read()
def Modify_rec():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\TCH.DAT", 'rb+')
r=int(input("Enter Teacher ID for modification: "))
try:
while True:
pos=f.tell()
rec=pickle.load(f)
if (rec[0]==r):
nm=input("Enter Name: ")
sj=input("Enter subject: ")
sl=int(input("Enter Salary: "))
ds=input("Enter Designation: ")
rec=[r,nm,sj,sl,ds]
f.seek(pos)
pickle.dump(rec,f)
found=1
except EOFError:
if found==0:
print("No record found")
else:
print("Record updates sucessfully")
f.close()
Modify_rec()
read()
C:\\Users\\LENOVO\\Desktop\\FILES\\
REVISION EXAM
QUESTION 33
import csv
def add():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\logindata.csv","w",newline='')
wr=csv.writer(f)
for i in range(1,6):
username=input("enter user name")
password=input("enter the password")
data=[username,password]
wr.writerow(data)
f.close()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\logindata.csv","r")
read=csv.reader(f)
for i in read:
print(i)
f.close()
add()
read()
def readdisp():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\logindata.csv","r")
username=input("enter user name")
read=csv.reader(f)
for i in read:
if(i[0]==username):
print(i[0],'\t',i[1])
f.close()
readdisp()
import csv
def write():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","w",newline='')
wr=csv.writer(f,delimiter=’\t’)
for i range(1,4):
n=input("enter country name")
g=int(input("enter the number of gold medals"))
s=int(input("enter the number of silver medals"))
b=int(input("enter the number of bronze medals"))
data=[n,g,s,b]
wr.writerow(data)
f.close()
def read():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
for i in read:
print(i)
f.close()
write()
read()
def find():
f=open("C:\\Users\\LENOVO\\Desktop\\FILES\\record.csv","r")
read=csv.reader(f)
cn=input("enter the country name ")
for i in read:
if(i[0]==cn):
s=int(i[1])+int(i[2])+int(i[3])
print(i[0],'\t',s)
f.close()
find()
Q27:
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\sample.txt",'r')
str=f.read()
count=0
words=str.split()
for i in words:
if len(i)==4:
count+=1
print(i[0])
f.close()
print(count)
countwords()
def countwords():
f=open(r"C:\Users\LENOVO\Desktop\FILES\updated.txt",'r')
str=f.read()
c1=0
c2=0
for i in str:
if i=='A'or i=='a':
c1+=1
if i=='M'or i=='m':
c2+=1
f.close()
print("A or a ",c1)
print("M or m ",c2)
countwords()