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

File handling programs

The document contains a series of Python programming tasks related to file handling, including reading and writing text and binary files, manipulating CSV files, and performing various data processing operations. Each task includes specific requirements and code snippets demonstrating how to implement the desired functionality. The tasks cover a wide range of topics, including counting characters, filtering data, and creating structured files.

Uploaded by

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

File handling programs

The document contains a series of Python programming tasks related to file handling, including reading and writing text and binary files, manipulating CSV files, and performing various data processing operations. Each task includes specific requirements and code snippets demonstrating how to implement the desired functionality. The tasks cover a wide range of topics, including counting characters, filtering data, and creating structured files.

Uploaded by

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

1.

Write a program that reads a text file and creates another file
that is identical except that every sequence of consecutive blank
spaces is replaced by a single space.
filel1= open("sample.txt","r") file1 = open("portal.txt","r")
file2 = open("New.txt","w") file2 = open("Express.txt","w")
lst= file1.readlines () lst = file1.readlines()
for i in lst:
for i in lst :
word = i.split()
file2.write("".join(word) ) word = i.split()
file2.write("\n") for j in word :
print("Program has successfully run") file2.write( j + "")
file2.close() file2.write("\n")
file1.close() print("Program has successfully run")
file2.close()
file1.close()

2. Write a function that would read contents from file sports.dat and
creates a file named Atheletic.dat copying only those records from
sports.dat where the event name is "Atheletics".

Binary File Program :


import pickle
def portal():
file1 = open("sports.dat", "rb")
file2 = open("Atheletics.dat", "wb")
try:
while True:
data = pickle.load(file1)
word = data.split("~")
if data [ : 9 ] == "atheletic" or data [ : 9 ] == "Atheletic":
pickle.dump(data, file2)
except EOFError:
file1.close ()
file2.close()
print("Program Run Succesfully !!")
portal ()

Text File Program:


def portal():
file1 = open("sports.txt","r")
file2 = open("Atheletics.txt", "w")
lst = file1.readlines ()
for i in lst :
print (i [: 9])
if i [:9] == "atheletic" or i[:9] == "Atheletic" :
file2.write(i)
file1.close()
file2.close()
portal ()

3. A file contains a list of telephone numbers in the following form:


Ravi 7258031
Sachin 7259197
The names contain only one word the names and telephone
numbers are separated by white spaces Write program to read a file
and display its contents in two columns.

print("Name\t|\tPhone no. ")


file = open("Path Walla.txt", "r")
lst = file.readlines()
for i in lst :
data = i.split()
print( data[0] ,end = "\t" )
print("|" , end = "\t")
print ( data[1] )
file.close()

4. Write a program to count the words "to" and "the" present in a


text file "Poem.txt".

to_no = 0
the_no = 0
file = open("Poem.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if j == "to" or j == "To" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1
print("Number 'to' : " , to_no)
print("Number 'the' : " , the_no)
file.close()

5. Write a function AMCount() in Python, which should read each


character of a text file STORY.TXT, should count and display the
occurrence of alphabets A and M (including small cases a and m
too).

def AMCount( ):
f = open("STORY.txt", "r",)
data = f.read()
count_a = 0
count_m = 0
for i in data :
if i == "a" or i == "A":
count_a += 1
elif i == "m" or i == "M":
count_m += 1
print("A or a :", count_a )
print("M or m:", count_m)
AMCount()

6. Write a program to count the number of upper- case alphabets


present in a text file "Article.txt".
count = 0
file = open("Article.txt","r")
sen = file.read()
for i in range ( len(sen) ) :
if sen[ i ].isupper() :
count += 1
print("Number of upper case alphabet : ", count)
file.close()

7. Write a program that copies one file to another. Have the


program read the file names from user ?

file1 = input("Enter the name of original file :- ")


file2 = input("Enter the name of New file :- : ")
old = open( file1 , "r")
new = open( file2, "w")
data = old.read()
new.write( data )
print(" Program run successfully ")
old.close()
new.close()

8. Write a program that appends the contents of one file to another.


Have the program take the filenames from the user.

file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
old = open( file2 , "r" )
new = open( file1 , "a" )
data = old.read()
new.write( "\n" + data)
print("Program run successfully ")
old.close()
new.close()

9. Write a method in python to read lines from a text file


MYNOTES.TXT, and display those lines, which are starting with an
alphabet 'K'.
Kangaroo is a mammal native to Australia.
Lion is a large carnivorous.
Koala is an arboreal herbivorous.
Elephant is a large herbivorous mammal.
def display_lines(file_name):
with open(file_name, 'r') as file:
line = file.readline()
while line:
if line.strip().startswith('K'):
print(line.strip())
line = file.readline()

display_lines("MYNOTES.TXT")

10. Write a method/function DISPLAYWORDS() in python to read


lines from a text file STORY.TXT, and display those words, which are
less than 4 characters.

def DISPLAYWORDS() :
file = open("story.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )
file.close()
print("Word with length smaller than 3 :- \n")
DISPLAYWORDS()

11. Write a program that reads characters from the keyboard one
by one. All lower case characters get stored inside the file LOWER,
all upper case characters get stored inside the file UPPER and all
other characters get stored inside file OTHERS.

upper = open("UPPER.txt","w")
lower = open("LOWER.txt" , "w" )
other = open ("OTHER.txt" , "w")
while True :
user = input("Enter a charracter (for exit enter quit ): ")
if user == "quit" or user == "Quit" :
break
elif user.isupper() :
upper.write( user + "" )
elif user.islower( ) :
lower.write( user + "" )
else :
other.write( user + "" )
upper.close()
lower.close()
other.close()
print("Thankyou")

12. Write a function in Python to count and display the number of


lines starting with alphabet 'A' present in a text file " LINES.TXT".
e.g., the file "LINES.TXT" contains the following lines:

A boy is playing there.


There is a playground.
An aeroplane is in the sky.

Alphabets & numbers are allowed in password.


The function should display the output as 3.

count = 0
file = open("LINES.txt","r")
lst = file.readlines()
for i in lst :
if i[ 0 ] == "A" :
print(i)
count += 1
print()
print("So for number of sentences started with A : ",count)
file.close()

13. Write a program that counts the number of characters up to the


first $ in a text file.

file = open("pathwalla.txt","r")
data = file.read()
for i in range( len( data ) ):
if data [ i ] == "$" :
break
print( "Total number of characters up to the first $ before = ",i )

14. Write a program that will create an object called filout for
writing, associate it with the filename STRS.txt. The code should
keep on writing strings to it as long as the user wants.
with open('STRS.txt', 'w') as filout:
ans = 'y'
while ans == 'y':
string = input("Enter a string: ")
filout.write(string + "\n")
ans = input("Want to enter more strings?(y/n)...")

15. Consider the following definition of dictionary Member, write a


method in python to write the content in a pickled file member.dat.
Member = {'MemberNo.': _____, 'Name': _____}
import pickle
file = open("member.dat","wb")
while True :
dic={}
no = int(input("Enter memberbno. :-"))
name = input("Enter name:-")
dic[ "Memberno."] = no
dic["Name"] = name
pickle.dump( dic, file )
user = input("For quit enter quit :-")
if user == "quit":
break
print("Thankyou")
file.close()

16. Consider the following definition of dictionary Staff, write a


method in python to search and display the content in a pickled file
staff.dat, where Staffcode key of the dictionary is matching with
'S0105'.
Staff = {‘Staff Code': _____, 'Name' = _____}

import pickle
file = open("staff.dat", "rb")
found = 0
try :
while True :
staff = pickle.load(file)
if staff [ "Staff Code" ] == 'S0105':
print(staff)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()

17. Considering the following definition of dictionary COMPANY,


Write a method in Python to search and display the content in a
pickled file COMPANY.DAT, where CompID key of the dictionary is
matching with the value '1005'.
Company = {'CompID' = ____, 'CName' = ____, ‘Turnover’ = ____}

import pickle
file = open("COMPANY.DAT","rb")
found = 0
try :
while True :
Company = pickle.load(file)
if Company [ "CompID" ] == '1005':
print(Company)
found=1
except EOFError :
if found == 0:
print("Not found !!!") a
file.close()

18. Write a function in to search and display details of all trains,


whose destination is Delhi from a binary file TRAIN.DAT. Assuming
the binary file is containing the objects of the following dictionary
type:
Train = { 'Tno': ___ , 'From': ____ , 'To' : ____}

import pickle
def search() :
file = open("TRAIN.DAT","rb")
found = 0
try :
while True :
Train = pickle.load(file)
if Train [ "To" ] == 'Delhi':
print(Train)
found=1
except EOFError :
if found == 0:
print("Not found !!!")
file.close()
search()

Program for writing in the binary file :


import pickle
f = open("TRAIN.DAT","wb")
while True :
Tno = int(input("Enter Train number ( -1 for exit ) :- "))
if Tno == -1 :
break
From = input("Enter Station name :- ")
To = input("Enter Station name where that train will go:- ")
Train = { 'Tno': Tno , 'From': From , 'To' : To }
pickle.dump( Train , f)
print("Your file is ready.")
f.close()

19. A binary file "Book.dat" has structure [BookNo, Book Name,


Author, Price].
(i) Write a user defined function CreateFile() to input data for a
record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the
Author name as a parameter and count and return number of books
by the given Author are stored in the binary file "Book.dat".

import pickle
def CreateFile():
f = open("Book.dat", "wb")
while True :
num = int(input("Enter Book Number :- "))
name = input ("Enter Book Name :- ")
aut = input("Enter Author :- ")
pri = float(input("Enter Price of Book :- "))
lst= [ num, name, aut, pri]
pickle.dump( lst, f)
choice = input("For exit (Enter exit):- ")
print()
if choice == "exit" or choice == "Exit":
print("Thank you")
print()
break
f.close()

def CoutRec(aut):
f = open("Book.dat", "rb")
count = 0
try :
while True:
data = pickle.load(f)
if data[2] == aut :
count += 1
except EOFError:
f.close()
print("Number of Book with Author name", aut , "=", count)
CreateFile()
print("For Searching -")
aut = input("Enter Author :- ")
CoutRec(aut)

20. Write a function Show_words() in python to read the content of a


text file "NOTES.TXT" and display only such lines of the file which
have exactly 5 words in them.
Example, if the file contains :

This is a sample file.


The file contains many sentences.
But need only sentences which have only 5 words.
Then the function should display the output as :
This is a sample file.
The file contains many sentences.

For Text file :


def Show_words():
f = open("notes.txt","r")
data = f.readlines()
for i in data :
words = i.split()
if len(words) == 5 :
print(i)
f.close()
Show_words()

For binary file :


import pickle
def Show_words():
f = open("NOTES.dat", "rb")
try :
while True:
line = pickle.load(f)
word = line.split()
if len( word ) == 5 :
print( line )
except EOFError:
f.close()
Show_words()

21. Write a Python program to read a given CSV file having tab
delimiter.
import csv
file = open( "Pathwalla.csv","r" )
data = csv.reader(file, delimiter = "\t")
for i in data :
print(i)
file.close()

22. Write a Python program to write a nested Python list to a csv file
in one go. After writing the CSV read the CSV file and display the
content.

import csv
file = open( "Portal.csv","w",newline="" )
lst = eval(input("Enter a nested list :- "))
path_write = csv.writer( file)
path_write.writerows( lst )
file.close()
print()
print("Content of Portal.csv :")
print()
file = open( "Portal.csv","r" )
data = csv.reader(file )
for i in data :
print(i)
file.close()

23. Write a function that reads a csv file and creates another csv file
with the same content, but with a different delimiter.

import csv
def Pathwalla( file1 ):
file2 = open( "Portalexpress.csv","w",newline="" )
portal_write = csv.writer( file2 , delimiter = "|")
data = csv.reader(file1)
for i in data :
if i[0][:5] != "check" :
portal_write.writerow( i )
file2.close()
file1 = open( "Pathwalla.csv","r" )
Pathwalla( file1 )
print ("Thank You !!")

24. Write a program to read the records of this csv file and display
them.

import csv
with open("compresult.csv", "r") as fh :
creader = csv.reader(fh)
for rec in creader:
print(rec)

25. Write a program to create a CSV file to store student data


(Rollno., Name, Marks). Obtain data from user and write 5 records
into the file.

import csv
fh = open("Student.csv", " w" )
stuwriter = csv.writer(fh)
stuwriter.writerow( ['Rollno', 'Name', 'Marks'] )
for i in range(5):
print("Student record", (i+1))
rollno = int(input("Enter rollno:"))
name = input("Enter name:") marks = float(input("Enter marks:"))
sturec = [rollno, name, marks]
stuwriter.writerow(sturec)
fh.close()

26. Write a program to create a csv file (compresult.csv) and write


the above data into it.

import csv
fh = open("compresult.csv", "w")
cwriter = csv.writer(fh)
compdata = [
['Name', 'Points', 'Rank'],
'Shradha', 4500, 23],
['Nishchay', 4800, 31],
['Ali', 4500, 25],
['Adi', 5100, 14] ]
cwriter.writerows(compdata)
fh.close()
27. Aman is a Python programmer. He has written a code and
created a binary file record dat with employee id, ename and salary.
The file contains 10 records.
He now has to update a record based on the employee id entered by
the user and update the salary. The updated record is then to be
written in the file temp.dat. The records which are not to be
updated also have to be written to the file temp.dat. If the
employee id is not found, an appropriate message should to be
displayed. As
a Python expert, help him to complete the following code based on
the requirement given above:

import Pickle
def update_data():
rec ={ }
fin =open( "record.dat" ,"rb")
fout=open("temp.dat", " w")
found=False
eid = int(input("Enter employee id to update their salary :: "))
while True:
try:
rec=pickle.load(fin)
if rec["Employee id"] == eid :
found = True
rec["Salary"] = int(input("Enter new salary :: "))
pickle. dump(rec, fout)
else:
pickle.dump(rec, fout)
except:
break
if found == True:
print("The salary of employee id ", eid," has been
updated.")
else:
print("No employee with such id is not found")
fin.close()
fout.close()

28. A binary file "STUDENT.DAT" has structure (admission number,


Name, Percentage), Write a function countr in Python that would
read contents of the file "STUDENT.DAT" and display the details of
those students whose percentage is above 75. Also display number
of students scoring above 75%.

import pickle
def CountRec():
fobj = open("STUDENT.DAT","rb")
num=0
try :
while True:
rec = pickle.load(fobj)
if rec[2] >75:
print(rec[0], rec[1], rec[2], sep= "\t")
num = num + 1
except:
fobj.close()
return num

29. Write a program to increase the salary by Rs. 2000/- of the


employee having empno as 1251 in the file empl.dat.

import pickle
emp={}
found=False
fin =open( empl.dat', 'rb+')
try:
while True :
emp =pickle. load(fin)
if emp['Empno"] == 1251:
emp['Salary'] = emp['Salary'] + 2000
pickle.dump(emp, fin)
print(emp)
found=True
except EOFError:
if found == False:
print("Sorry, no matching record found.")
else:
print("Record(s) successfully updated.")
fin.close()

30. What is the advantage of using a csv file for permanent storage?
Write a Program in Python that defines and calls the following user
defined functions:

a) ADD() – To accept and add data of an employee to a CSV file


‘record.csv’. Each record consists of a list with field elements as
empid, name and mobile to store employee id, employee name and
employee salary respectively.

b) COUNTR() – To count the number of records present in the CSV


file named ‘record.csv’.

Advantage of a csv file:


It is human readable – can be opened in Excel and Notepad applications It
is just like text.

31. Give any one point of difference between a binary file and a CSV
file.

Write a Program in Python that defines and calls the following user
defined functions :

(a) add(). To accept and add data of an employee to a CSV file


'furdata.csv'. Each record consists of a list with field elements as fid,
fname and fprice to store furniture id, furniture name and furniture
price respectively.

(b) search(). To display the records of the furniture whose price is


more than 10000.

The difference between a binary file and CSV file is that binary files are used
for storing complex data in a non-human-readable format and they store
data in a sequence of bytes, while CSV files are plain text files used for
storing structured tabular data in a human-readable text format.

Let the file "furdata.csv" include following data:

[1, table, 20000]


[2, chair, 12000]
[3, board, 10000]
import csv
def add():
f1= open('furdata.csv', 'a')
writer = csv.writer(f1)
fid = input("Enter furniture id: ")
fname = input("Enter furniture name: ")
fprice = float(input("Enter furniture price: "))
writer.writerow([fid, fname, fprice])
print("Record added successfully to 'furdata.csv'")

def search():
found = False
f1= open('furdata.csv', 'a')
reader = csv.reader(f1)
print("Records of furniture with price more than 10000:")
for row in reader:
if len(row) == 3 and float(row[2]) > 10000:
print("Furniture ID:", row[0])
print("Furniture Name:", row[1])
print("Furniture Price:", row[2])
print()
found = True

if found == False:
print("No records of furniture with price more than 10000 found")

add()
search()

32. Write a function that reads a csv file and creates another csv file
with the same content except the lines beginning with 'check'.

import csv
def filter(input_file, output_file):
fin = open(input_file, 'r',)
fout= open(output_file, 'w',)
reader = csv.reader(fin)
writer = csv.writer(fout)

for row in reader:


if row[0].startswith('check'):
writer.writerow(row)

filter('input.csv', 'output.csv')

You might also like