Exercise File

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Q.

Write a program that reads a text file and creates another file t

hat is identical except that every sequence of consecutive blank spaces is replaced by a single space.

file1 = open("portal.txt","r")
file2 = open("Express.txt","w")

lst = file1.readlines()

for i in lst :
word = i.split()
file2.write( " ".join(word) )
file2.write("\n")

print("Program has successfully run")

file2.close()
file1.close()
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 .

Q. A file sports.dat contains information in following format :

Event ~ Participant

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 ".

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()
A file contains a list of telephone numbers in the following form: 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.

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

Arvind 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 | Phone no. ")

file = open("portal.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()

Q. 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" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

file.close()

Q. Write a program to count the number of upper- case alphabets present in a text file "Article.txt".

count = 0

file = open("pathwala.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()
Q. Write a program that copies one file to another. Have the program read the file names from
user ?

file = input("Enter the name of file with its formate : ")

old = open( file , "r")


new = open("New file.txt", "w")

data = old.read()
new.write( data )

print(" Program run successfully ")

old.close()
new.close()
Q. 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()

DISPLAYWORDS()

Q. 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()

DISPLAYWORDS()
Q. 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")

Q. 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("So for number of sentences started with A : ",count)

file.close()
Q. Write a program that counts the number of characters up to the first $ in a text file.

file = open("Pathwala.txt","r")

data = file.readlines()

for i in range( len( data ) ):


for j in range( len( data[ i ] ) ):
if data [ i ][ j ] == "$" :
break

print( "Total number of characters up to the first $ befor = ",i+j )


file.close()
Q. 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.

file1 = open("portal.txt","r")
file2 = open("Express.txt","w")

lst = file1.readlines()

for i in lst :
word = i.split()
file2.write( " ".join(word) )
file2.write("\n")

print("Program has successfully run")

file2.close()
file1.close()
Q. 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" :
to_no += 1
elif j == "the" or j == "The" :
the_no += 1

print("Number 'to' : " , to_no)


print("Number 'the' : " , the_no)

file.close()
Q. 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()

Q. 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()

Q. 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’ = ____}

Answer =

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 !!!")

file.close()

Q. 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' : ____}

Answer =

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()

Q. Write a Python program to read a given CSV file having tab delimiter.

Answer =

import csv
file = open( "Pathwala.txt","r" )
data = csv.reader(file, delimiter = "|")
for i in data :
print(i)

file.close()

Q. 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.

Answer =

import csv

file = open( "Pathwala.txt","r+" )


lst = eval(input("Enter a nested list :-"))
path_write = csv.writer( file)
path_write.writerows( lst )

data = csv.reader(file)
for i in data :
print(i)

file.close()
Q. Write a function that reads a csv file and creates another csv file with the same content, but with
a different delimiter.

Answer =

import csv

file1 = open( "Pathwala.txt","r" )


data = csv.reader(file1)

file2 = open( "Portalexpress.txt","w",newline="" )


portal_write = csv.writer( file2 , delimiter = "|")
portal_write.writerows( data )

file2.close()

Q. 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.

Answer =

import csv

file = open( "Pathwala.txt","r+" )


lst = eval(input("Enter a nested list :-"))
path_write = csv.writer( file)
path_write.writerows( lst )

data = csv.reader(file)
for i in data :
print(i)

file.close()
HomeFile Handling

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

file1 = open( "Pathwala.txt","r" )


data = csv.reader(file1)

file2 = open( "Portalexpress.txt","w",newline="" )


portal_write = csv.writer( file2 , delimiter = "|")
portal_write.writerows( data )

file2.close()
Q. Write a function that reads a csv file and creates another csv file with the same content except the
lines beginning with 'check'.

Answer =

import csv
file1 = open( "Pathwala.txt","r" )
file2 = open( "Portalexpress.txt","w",newline="" )
portal_write = csv.writer( file2 , delimiter = "|")

data = csv.reader(file1)

for i in data :
portal_write.writerow( ["Check"] + i )

file2.close()

You might also like