good morning,
you are learning python
Text file
It's a very simple language to learn.
Program: to calculating size of file with and without EOL and Blank lines:-
f=open("C:\\h1.txt","r")
str1=" "
size=0
tsize=0
while str1:
str1=f.readline()
tsize=tsize+len(str1)
size=size+len(str1.rstrip())
print("total size : ",tsize)
print("Size after removing al EOL and blank lines : ",size)
f.close()
O/P:-
total size : 75
Size after removing al EOL and blank lines : 73
Program: to calculating lines of file:-
f=open("C:\\h1.txt","r")
str=f.readlines()
lines=len(str)
print("number of lines in file : ",lines)
f.close()
O/p:-
number of lines in file : 3
Program:- WAP to read the content of file and count how many times letter 'a’ comes in file.
f=open("C:\\h1.txt","r")
word=f.read()
occurence=word.count("a")
print("Letter 'a' showing : ",occurence, "Times.")
f.close()
O/p:-
Letter 'a' showing : 6 Times.
------------------------------
OR
def count_letter():
count=0
f=open("C:\\h1.txt","r")
content=f.read()
for w in content:
if w=='a' or w=='A':
count=count+1
print(count)
f.close()
count_letter()
Program:- WAP to read the content of file and show total number of vowel, consonant,
uppercase, lower case and number of digits are there in the given file:-
f=open("D:\\test1.txt")
word=f.read()
vowel = consonent = uppercase = lowercase= digit=0
for i in word:
if(i == 'a' or i == 'e' or i == 'i' or i == 'o' or i ==
'u'or i == 'A' or i == 'E' or i == 'I' or i == 'O' or i ==
'U'):
vowel = vowel +1
else:
consonent = consonent + 1
if i.isupper() :
uppercase = uppercase + 1
elif i.islower():
lowercase = lowercase + 1
elif i.isdigit():
digit=digit+1
print("Total number of vowel:",vowel)
print("Total number of consonent:",consonent)
print("Total number of uppercase letter:",uppercase)
print("Total number of lowercase letter:",lowercase)
print("Total number of DIGITS are:", digit)
f.close()
Program:- WAP to read the content of file and display number of words in file :-
f = open("C:\data.txt", "r")
data = f.read()
words = data.split()
print('Number of words in text file :', len(words))
O/p:-
Number of words in text file : 16
Program:- WAP to read the particular line number from text file.
Persistent program is one type of
File. Text file
File handling has many mode.
3432432432
READ, WRITE, APPEND
f=open("D:\\h3.txt","r")
contents=f.readlines()
print(contents)
print("-------------------")
print("first line is : ",contents[0])
print("Second line is : ",contents[1])
print("last line is : ",contents[4])
f.close()
O/p:-
['Persistent program is one type of \n', 'File.\n', 'File
handling has many mode.\n', '3432432432\n', 'READ, WRITE,
APPEND\n']
-------------------
first line is : Persistent program is one type of
Second line is : File.
last line is : READ, WRITE, APPEND
Program:- Write a function ISTOUPCOUNT() in python to read the content of file writer.txt,
to count and display the occurrence of IS, TO, UP.
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING.
text file
IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE
RESPONSIBILITY.
def ISTOUPCOUNT():
c=0
f=open("D:\\test1.txt","r")
line=f.read()
word=line.split()
for w in word:
if w=='IS' or w =="TO" or w =="UP":
c=c+1
print("total words count :",c)
f.close()
ISTOUPCOUNT()
o/p:-
total words count : 5
Program:- write()
f=open("write1.txt","w")
f.write("I like to learn python.")
f.write("it's a text file \n jhgjghjugh \n ytreytryrtyrtyrtyryhfghfh")
f.write("use of write function")
f.close()
Program:- Properties of file object:-
f=open("C:\\h1.txt")
print("File name: ",f.name)
print("file mode : ",f.mode)
print("Encoding format of file : ",f.encoding)#return encoding
#format of the file.
print("file is closed ? : ",f.closed)
f.close()
print("file is closed ? : ",f.closed)
print("File is closed now")
O/p:-
File name: C:\h1.txt
file mode : r
Encoding format of file : cp1252
file is closed ? : False
file is closed ? : True
File is closed now
Program:- Create COUNTAE()function to count and read lines starting with letter “A” or “E”
only:-
A clean environment is necessary for good health.
We should keep clean it.
Educational institute should take the lead.
def COUNTAE():
f=open("D:\\h3.txt","r")
l=f.readlines()
lines = 0
for ch in l:
if ch[0] =="A" or ch[0]=="E":
lines+=1
print(lines)
f.close()
COUNTAE()
O/p:-
2
Program:- Addition of two numbers using file handling:-
f=open("addi.txt","w")
n1=int(input("enter n1 : "))
n2=int(input("enter n2 : "))
sum=n1+n2
f.write("number1 :"+str(n1))
f.write("number2 :"+str(n2))
f.write("Addition : "+str(sum))
print(sum)
f.close()
O/P:
enter n1 : 96
enter n2 : 87
183 (It will create text file also)
Program: Use of write() function:-
f=open("w1.txt","w")
for i in range(3):
name=input("enter name : ")
f.write(name)
f.write('\n')
f.close()
print("\n Data entered successfully...")
O/P:-
enter name : aaa
enter name : bbb
enter name : ccc
Data entered successfully...
Program: Using writelines():-
f=open("writeliness1.txt","w")
list=["computer science \n","Account \n","Physics Biology",
"Chemistry \n","English"]
f.writelines(list)
f.close()
O/p:-
(in the notepad file we can see…..)
computer science
Account
Physics Biology Chemistry
English
Program:- Writing String as a record to file:-
f=open("book.txt","a")
ans='y'
while ans=='y':
bno=int(input("enter book number : "))
bname=input("enter book name : ")
author=input("enter author name : ")
Program:- Writing String as a record to file:-
f=open("book.txt","a")
ans='y'
while ans=='y':
bno=int(input("enter book number : "))
bname=input("enter book name : ")
author=input("enter author name : ")
price=int(input("enter book price : "))
display=str(bno)+" , "+bname +" , "+author+" ,
"+str(price)+ "\n"
f.write(display)
ans=input("Want to add more? : ")
f.close()
O/P:-
1001 , python , xyz , 956
2002, Computer science, abc, 1000
Program:- To copy the content from one file to another text file:-
f=open("D:\\w1.txt","r")
c=open(“D:\\w1copy.txt”,”w”)
str1=" "
while str1:
str1=f.readline()
c.write(str1)
f.close()
c.close()
print(“Copied successfully……”)
Program:- WAP to read the particular line number from text file.
Persistent program is one type of
File. Text file
File handling has many mode.
3432432432
READ, WRITE, APPEND
f=open("D:\\h3.txt","r")
contents=f.readlines()
print(contents)
print("-------------------")
print("first line is : ",contents[0])
print("Second line is : ",contents[1])
print("last line is : ",contents[4])
f.close()
O/p:-
['Persistent program is one type of \n', 'File.\n', 'File
handling has many mode.\n', '3432432432\n', 'READ, WRITE,
APPEND\n']
-------------------
first line is : Persistent program is one type of
Second line is : File.
last line is : READ, WRITE, APPEND
Program:- Write a function ISTOUPCOUNT() in python to read the content of file writer.txt,
to count and display the occurrence of IS, TO, UP.
IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING.
text file
IT IS NOT POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE
RESPONSIBILITY.
def ISTOUPCOUNT():
c=0
f=open("D:\\test1.txt","r")
line=f.read()
word=line.split()
for w in word:
if w=='IS' or w =="TO" or w =="UP":
c=c+1
print("total words count :",c)
f.close()
ISTOUPCOUNT()
o/p:-
total words count : 5
Program:- write()
f=open("write1.txt","w")
f.write("I like to learn python.")
f.write("it's a text file \n jhgjghjugh \n ytreytryrtyrtyrtyryhfghfh")
f.write("use of write function")
f.close()
Program:- Properties of file object:-
f=open("C:\\h1.txt")
print("File name: ",f.name)
print("file mode : ",f.mode)
print("Encoding format of file : ",f.encoding)#return encoding
#format of the file.
print("file is closed ? : ",f.closed)
f.close()
print("file is closed ? : ",f.closed)
print("File is closed now")
O/p:-
File name: C:\h1.txt
file mode : r
Encoding format of file : cp1252
file is closed ? : False
file is closed ? : True
File is closed now
Program:- Create COUNTAE()function to count and read lines starting with letter “A” or “E”
only:-
A clean environment is necessary for good health.
We should keep clean it.
Educational institute should take the lead.
def COUNTAE():
f=open("D:\\h3.txt","r")
l=f.readlines()
lines = 0
for ch in l:
if ch[0] =="A" or ch[0]=="E":
lines+=1
print(lines)
f.close()
COUNTAE()
O/p:-
2
Program:- Addition of two numbers using file handling:-
f=open("addi.txt","w")
n1=int(input("enter n1 : "))
n2=int(input("enter n2 : "))
sum=n1+n2
f.write("number1 :"+str(n1))
f.write("number2 :"+str(n2))
f.write("Addition : "+str(sum))
print(sum)
f.close()
O/P:
enter n1 : 96
enter n2 : 87
183 (It will create text file also)
Program:- Addition of two numbers using file handling:-
def COUNTAE():
f=open("D:\\h3.txt","r")
l=f.readlines()
lines = 0
for ch in l:
if ch[0] =="A" or ch[0]=="E":
lines+=1
print(lines)
f.close()
COUNTAE()
File handling:- Binary file
Program : to write list in a binary file using function:-
def test():
import pickle
list1=[10,20,"abc",34.5]
f=open("list1.dat","wb")
pickle.dump(list1,f)
print("list added to binary file: ")
f.close()
test()
Program : to write list in a binary file without function:-
import pickle
list1=[10,20,"abc",34.5]
f=open("list1.dat","wb")
pickle.dump(list1,f)
print("list added to binary file: ")
f.close()
Program : to write dictionary to a binary files:-
import pickle
dict1={'python':90,'java':85,'c++':80}
f=open("dictintobinary.dat","wb")
pickle.dump(dict1,f)
print("enter successfully")
f.close()
Program : To read from binaryfile:-
import pickle
f=open("list1.dat","rb")
dict1=pickle.load(f)
f.close()
print(dict1)
Program: for inserting/appending a record in a binary file-“student.dat”:-
Steps:-
To append data in binary follow these steps:
Open the file in append mode using “ab” or “rb” Ex.: f = open (“file.dat”,”ab”)
Declare list object to store data which is going to be appended
Enter data to append
Append entered data into the declared list object
Use pickle.dump() method to write the list data
Close the file
Program:-
import pickle
record=[]
while True:
rollno=int(input("enter no : "))
name=input("enter the student name : ")
marks=int(input("enter marks : "))
data=[rollno,name,marks]
record.append(data)
choice=input("Do you want to enter more records?(Y/N) : ")
if choice=='n' or choice=='N':
break
f=open("student.dat","wb")
pickle.dump(record,f)
print("record added")
f.close()
Output:-
Program: To read above data with simple way:-
import pickle
f=open("student","rb")
data=pickle.load(f)
f.close()
print(data)
Program: To read above program with for loop:-
Follow these steps to read data:
Open the file in read mode using “rb” Ex.: f = open(“File.dat”, “rb”)
Use while loop with True statement OR for loop to read the entire
contents of the file.
(Use try – except for Exception handling to avoid runtime error—if using
while loop)
Now load data in an object through load function
Use loop to access data individually
Close the file
import pickle
f=open("student.dat","rb")
data=pickle.load(f)
print("Contents of the files: ")
#reading the fields from the file--
for r in data:
no=r[0]
name=r[1]
mark=r[2]
print(no,name,mark)
f.close()
STEPS to search a record from the binary file - "student.dat"
Open the file in reading mode using “rb”
Now load the data into the data log variable using load() function
Declare a variable to store 0(zero) for the record not found and 1 when record
found, assign 0
Prompt a message to ask unique field from data to search
Take for loop to check the record is available or not in the file.
Use if condition to compare the data with the variable taken in step 4
Print the record found
Assign 1 to the variable declared in step 3
Use the break to terminate the loop
Now provide a message using if condition if the record not found.(variable==0)
Program to search a record from the binary file - "student.dat":-
import pickle
f=open("student.dat","rb")
data=pickle.load(f)
found=0
rno=int(input("enter roll number to search : "))
for r in data:
if r[0]==rno:
print("Record is successful",r[0],r[1],"Result found")
found=1
break
if found==0:
print("no match")
f.close()
Output:-
In Python, seek() function is used to change the position of the File
Handle(file pointer) to a given specific position. File handle is like a cursor,
which defines from where the data has to be read or written in the file.
Program to update the name of student from binary file:
Open the file using read mode “rb”
Now load the data into the data log variable using load() function
Declare a variable to store 0(zero) for the record not found and 1 when
record found, assign 0
Prompt a message to ask unique field from data to search and update
Take for loop to check the record is available or not in the file.
Use if condition to compare the data with the variable taken in step 4
Increase the value by 1. (Assign 1 to the variable declared in step 3)
Use the break to terminate the loop
Use one more if condition out of the for loop if value==1
Now again place the cursor at current position using seek() function
Write the data using dump() function.
Program:-
import pickle
f=open("student.dat","rb")
data=pickle.load(f)
found=0
rno=int(input("enter roll number to search : "))
for r in data:
if rno==r[0]:
print("Current name: ",r[1])
r[1]=input("New name : ")
found=1
break
if found==1:
f.seek(0)
pickle.dump(data,f)
print("name updated.... ")
f.close()
OUTPUT:-
Program to delete the records of student from binary file:
1. Declare variable as a null list
2. Open the file in reading mode
3. Load data using the load function
4. Print current data(before delete operation)
5. Close file
6. Now open the same file again with writing mode. (you can take same name for the file
pointer)
7. Declare another variable as False
8. Prompt a message to delete a record with a variable
9. Declare one more variable as a null list.OR( Declare a list object to store data from the file)
10. Use for loop and if condition as used in the update and delete, try-except is not necessary
11. Now append the data into a list object
12. Write data using the dump method
13. Close the file
14. Open the same file again for the third time in read mode.
15. Load data using the load function
16. Print the remaining records from the file.
#Program to delete the record of student from binary file:
import pickle
reclst=[]
f = open("student.dat","rb")
reclst=pickle.load(f)
print("records")
print(reclst)
f.close()
f=open("student.dat","wb")
found=False
rn=int(input("Enter number to delete records"))
reclst2=[]
for i in range(len(reclst)):
if reclst[i][0]!=rn:
reclst2.append(reclst[i])
pickle.dump(reclst2,f)
f.close()
f=open("student.dat","rb")
reclst=pickle.load(f)
print("after deleting records.....")
print(reclst)
Program to get the current working directory (To know absolute path)
import os
pwd = os.getcwd()
print("Current Directory :",pwd)
Program : To read “student.cvs” file contents:-
import csv
f=open("student.csv","r")
data_read=csv.reader(f)
for row in data_read:
print(row)
f.close()
Output:-
['1', 'aaa', 'a']
['2', 'bbb', 'a+']
['3', 'ccc', 'b+']
Program : To read “student.cvs” file using ‘with open()’:-
import csv
with open("f1.csv","r") as f:
data_read=csv.reader(f)
rows=[]
for rec in data_read:
rows.append(rec)
print(rows)
f.close()
Output:-
[['1', ' abc', ' satellite', ' 98'], ['2', ' xyz', ' paldi', ' 90'], ['3', ' pqr', ' navarangpura', ' 85']]
Program : To count the number of records present in above csv file:-
import csv
f=open("f1.csv","r")
read_data=csv.reader(f)
c=0
for row in read_data:
c=c+1
print("Number of records are : ",c)
f.close()
Output:-
Number of records are : 3
Program : To print records in the form of comma separated values:-
import csv
f=open("f1.csv","r")
data_reader=csv.reader(f)
for row in data_reader:
print(",".join(row))
f.close()
Output:-
1, abc, satellite, 98
2, xyz, paldi, 90
3, pqr, navarangpura, 85
Program :- Search any records based on roll number:-
import csv
f=open("f1.csv","r")
data_reader=csv.reader(f)
found=0
no=input("Enter the number to be search: ")
for row in data_reader:
if (row[0]==no):
print(row)
found=1
break
if found==0:
print("no match found")
f.close()
Output:-
Enter the number to be search: 3
['3', ' pqr', ' navarangpura', ' 85']
Program :- Search any records based on name:-
import csv
f=open("f1.csv","r")
data_reader=csv.reader(f)
found=0
name=input("Enter the name to be search: ")
for row in data_reader:
if (row[1]==name):
print(row)
found=1
break
if found==0:
print("no match found")
f.close()
Program :- Write student data onto a csv file:-
"""
Steps:-
1) importing csv module
2) create heading of the file(variable=['name','number']
3) enter details (multiple rows) of that file (variable=[['ram','23233322'],['rita','455435435']]
4) declare a name with csv extension for csv file.
5) open the csv file using file handler
6) use writer() function to obtain a writer object and store it in the the
vaiable csv_w as the name of the variable and this is the csv object.
7) use writerows() method to write all the rows in one go, so that no need to
use loop and other iteration.
"""
import csv
fields=['name','class','year']
rows=[['raj','12','2021'],['sima','11','2022'],['pooja','12','2020']]
filename='student.csv'
f=open(filename,"w",newline='')
# bydefault, newline is \r\n
#Creating a csv writer object
csv_w=csv.writer(f)
#writing the fields (first write the column heading)
csv_w.writerow(fields)
for i in rows:
#writing the data row-wise
csv_w.writerow(i)
print("Check your ecel file, Data entered")
f.close()
Output:-
Check your excel file, Data entered
Program :- Write student data onto a csv file without for loop:-
import csv
fields=['name','class','year']
rows=[['raj','12','2021'],
['sima','11','2022'],
['pooja','12','2020']]
with open('student1.csv','w') as f:
# bydefault, newline is \r\n
#Creating a csv writer object
csv_w=csv.writer(f)
#writing the fields (first write the column heading)
csv_w.writerow(fields)
csv_w.writerow(rows)
print("Check your excel file, Data entered")
Output:-
Program : Write a program to add(append) employee records such as
employee number, name, salary onto a CSV file.
import csv
with open('student1.csv','a') as f:
csv_w=csv.writer(f,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter number : "))
ename=input("enter name : ")
salary=int(input("Enter Salary : "))
csv_w.writerow([eno,ename,salary])
print("Data saved")
ans=input("Add more")
DATA STRUCUTRE
Program:-
In a list perform push, pop and traversal operation (STACK):-
Out put of the above program.
Prepared By : Karishma Patel
Linear search (ONLY FOR KNOWLEDGE OF LINEAR STRUCTURE)
OUTPUT:-
Prepared By : Karishma Patel
Prepared By : Karishma Patel