Вы находитесь на странице: 1из 14

30.

Create and open a datafile. Read from this file and write to it.

def file_creation():
ofile = open('Sid.txt','a')
choice = True
while True:
line = raw_input('Enter sentence: ')
ofile.writelines(line + '\n')
choice = raw_input('Want to enter more data in file? y/n: ')

if (choice == 'n'):
ofile.close()
break

def file_display():
print ''
file = open('Sid.txt','r')
l = file.readlines()
for i in l:
print i
file.close
print ''

while True:
print '1. Writing to a file'
print '2. Reading from a file'

print '3. Exit'


ch = input('Enter your choice: ')
if ch == 1:
file_creation()
elif ch == 2:
file_display()
elif ch=='n':
break
Output:1. Writing to a file
2. Reading from a file
3. Exit
Enter your choice: 1
Enter sentence: Siddhant Tiwari
Want to enter more data in file? y/n: y
Enter sentence: XII-A
Want to enter more data in file? y/n: n
1. Writing to a file
2. Reading from a file
3. Exit
Enter your choice: 2
Siddhant Tiwari
XII-A
31. Program to count word do/DO in a file memo.txt.

import os

def countdo():
if os.path.isfile('memo.txt'):
fobj = open('memo.txt','r')
count = 0
print 'The contents of file are:\n'
while True:
line = str(fobj.readline())
print line,
if not line:
break
line = line.lower().strip()
wordlist = line.split()
for i in range(len(wordlist)):
if wordlist[i] == 'do' or wordlist[i] == 'do.':
count += 1
print "\n\nNumber of 'do' in file is",count
else:
print '\nFile does not exist'
countdo()
Output :The contents of file are:
Mom: You should do your work on time.
Son: Okay! I will do it.
Number of 'do' in file is 2 '''

32. Write a program to count lines and blank spaces in a text file
notes.txt.

import os
def Count():
if os.path.isfile('notes.txt'):
fobj = open('notes.txt','r')
space = ln = 0
print 'File contents are:\n'
while 1:
line = fobj.readline()
if not line:
break
else:
line = line.strip()
print line
ln += 1
for i in line:
if i.isspace():
space += 1
print 'Number of lines:',ln
print 'Number of spaces:',space
fobj.close()
else :
print 'File does not exist'
Count()
Output:-

File contents are:

Python is my favourite computer language.


It is so easy to understand and learn.

Number of lines: 2
Number of spaces: 12 '''
33. Create a binary file Directory such that
'Directory.dat' (binary file) is created and data is dumped and loaded from
it.Additionally phone numbers starting with number '2' are dumped into
another file 'mtnl.dat'.

import os
from pickle import load,dump
class phonelist():
def __init__(self):
self.pno = 0
self.name = ''
self.add = ''
def Input(self):
self.pno = int(input('Enter phone no: '))
self.name = raw_input('Enter name: ')
self.add = raw_input('Enter address: ')
def show(self):
print self.pno,',',self.name,',',self.add
def enter():
with open('Directory.dat','ab+') as mobj:

## File object - mobj

if not mobj:
print 'File does not exist'
else:
m = phonelist()

## m is object of class 'phonelist'

while True:
m.Input()
dump(m,mobj)
ch = raw_input('Wanna enter more? Y/N: ')
print ''
if ch.upper() == 'N':
break
## Function to dump data having phone no. starting with 2 in 'mtnl.dat'
def shift_mtnl():
if not os.path.isfile('Directory.dat'):
print 'Directory.dat','File does not exist'
else:
with open('Directory.dat','rb') as mobj:
tobj = open('mtnl.dat','wb')
try:
while True:
m = load(mobj)
strpno = str(m.pno)
if strpno[0] == '2':
m.show()
dump (m,tobj)

except EOFError:
print ''

## For clarity in output

pass
tobj.close()
while True:
print '1. Enter phone record'
print '2. Display phone record'
print '3. Copy MTNL (Digit - 2) phone number in mtnl.dat'
print '4. Exit'
ch = 0
ch = input('Enter choice: ')
print ''

## For clarity in output

if ch == 1:
enter()

## calling function 'enter' above

elif ch == 2:
if not os.path.isfile('Directory.dat'):
print 'Directory.dat','file does not exist'
else:
mobj = open('Directory.dat','rb')
try:
while True:
m = load(mobj)
m.show()
except EOFError:
print ''
pass

## For clarity in output

## File object - mobj

mobj.close()
elif ch == 3:
shift_mtnl()
elif ch == 4:
break
Output :1. Enter phone record
2. Display phone record
3. Copy MTNL (Digit - 2) phone number in mtnl.dat
4. Exit
Enter choice: 1
Enter phone no: 2350145678
Enter name: Raghu
Enter address: B-58 Tilak Nagar, New Delhi
Wanna enter more? Y/N: y
Enter phone no: 8526478963
Enter name: Siddhant
Enter address: W-07 Uttam Nagar, New Delhi
Wanna enter more? Y/N: n
1. Enter phone record
2. Display phone record
3. Copy MTNL (Digit - 2) phone number in mtnl.dat
4. Exit
Enter choice: 2
2350145678 , Raghu, B-58 Tilak Nagar, New Delhi
8526478963 , Siddhant, W-07 Uttam Nagar, New Delhi

1. Enter phone record


2. Display phone record
3. Copy MTNL (Digit - 2) phone number in mtnl.dat
4. Exit
Enter choice: 3
2350145678 , Raghu, B-58 Tilak Nagar, New Delhi
34. Create a binary file 'drink.dat' to store drink name, quantity & price &
hence search for mango drinks.

import os
from pickle import load, dump
bfile = 'drink.dat'
class drink:
def __init__(self):
self.dname = ''
self.qty = 0
self.price = 0.0
def getdrink(self):
self.dname = raw_input('Enter drink name: ').lower()
self.qty = input('Enter quantity (50/100/250!): ')
self.price = input('Enter drink price: ')
def showdrink(self):
print self.dname, ', Quantity -' ,self.qty, ', Price -' ,self.price
def write_drink():
with open('drink.dat','ab+') as dobj:
if not dobj:
print ('File does not exist')

else:
dr = drink()
while True:
dr.getdrink()
dump(dr,dobj)
ch = raw_input('Wanna enter more data? Y/N: ')
if ch.upper() == 'N':
break
def view_mango():
if not os.path.isfile(bfile):
print bfile,'File does not exist'
else:
with open(bfile,'rb') as dobj:
try:
print '\nMango drinks...\n'
while True:
dr = load(dobj)
ldrink = dr.dname
llist = ldrink.split()
for i in range (len(llist)):
if llist[i] == 'mango':
dr.showdrink()
except EOFError:
pass
while True:
print '1. Enter Drinks'

print '2. Display drinks'


print '3. Search Mango drinks'
print '4. Exit'
ch = 0
ch = input('Enter choice: ')
if ch == 1:
write_drink()
elif ch==2:
if not os.path.isfile(bfile):
print bfile,'File doesnot exist'
else:
dobj = open(bfile,'rb')
try:
print ''
while True:
dr = load(dobj)
dr.showdrink()
except EOFError:
pass
dobj.close()
elif ch == 3:
view_mango()
elif ch == 4:
break
Output:1. Enter Drinks

2. Display drinks
3. Search Mango drinks
4. Exit
Enter choice: 1
Enter drink name: Mango
Enter quantity (50/100/250!): 100
Enter drink price: 60
Wanna enter more data? Y/N: y
Enter drink name: Pepsi
Enter quantity (50/100/250!): 250
Enter drink price: 40
Wanna enter more data? Y/N: Y
Enter drink name: Coke
Enter quantity (50/100/250!): 50
Enter drink price: 50
Wanna enter more data? Y/N: n
1. Enter Drinks
2. Display drinks
3. Search Mango drinks
4. Exit
Enter choice: 2
Mango , Quantity - 100 , Price - 60
Pepsi , Quantity - 250 , Price - 40
Coke , Quantity - 50 , Price - 50
1. Enter Drinks
2. Display drinks

3. Search Mango drinks


4. Exit
Enter choice: 3

Mango drinks...

mango , Quantity - 100 , Price - 60


1. Enter Drinks
2. Display drinks
3. Search Mango drinks
4. Exit
Enter choice: 4
35. Program to count number of lines starting with A in lines.txt .

import os
file1 = 'lines.txt'
def countA(): ##Function to count number of lines starting with 'A'
if os.path.isfile(file1):
fobj = open(file1,'r')
ctr = 0
while 1:
line = fobj.readline() ##Read a line
line = line.lstrip()
print line,
if not line:
break

if line[0] == 'A':
ctr += 1
if ctr > 0:
print "Total lines staring with alphabet 'A' is",ctr
else:
print "There's no line starting with 'A'"
fobj.close

else:
print "File does not exist."
countA()
Output:A true friend sees the 1st tear, catches the 2nd, and stops the 3rd!!
We become what we criticize.
C for Cow
A program of no use?
Total lines staring with alphabet 'A' is 2 '''

Вам также может понравиться