Core Python Programming second edition of after-school exercise ninth chapter

9–1.   File filter. Display all the lines from a file, neglected to well number (#) the beginning of the line. This character is used as Python, Perl, Tcl, annotation symbols are script file.

Additional questions: treatment did not begin the first character of the notes.

 1 def outputfiles2(filename):
 2     f=open(filename,'r')
 3     for eachLine in f:
 4         index=eachLine.find('#')
 5         if index!=-1:
 6             if 0==index:continue
 7             else:
 8                 line=eachLine[0:index]
 9                 print line;continue
10         print eachLine,
11     f.close()
12 
13 outputfiles2('backup.py')

9–2.   File access. Prompt for digital N and F file, and then display the file N F.

 1 def outputfiles3(filename,number):
 2     f=open(filename,'r')
 3     n=0
 4     for eachLine in f:
 5         print eachLine,
 6         n+=1
 7         if n>=number:break
 8     f.close()
 9 
10 outputfiles3('backup.py',10)

9–3.   File information. Enter a file name, and then displays the number of head office of this text file.

1 def filenumber(filename):
2     f=open(filename,'r')
3     print len(f.readlines())
4     f.close()
5 
6 filenumber('backup.py')

9–4.   File access. Write a page by page to display text files. Enter a file name, each display 25 lines of text files, pause and presented to the user "press any key to continue.", continue to implement the key.

 1 import os
 2 def showTextbyPage(filename):
 3     f=open(filename,'r')
 4     n=0
 5     for eachLine in f:
 6         print eachLine,
 7         n+=1
 8         if n%25==0:
 9             os.system('pause')
10             continue
11     f.close()
12 
13 showTextbyPage('backup.py')

9–6.   Document. Write a two text files. If different, gives the first difference of row and column number.

 1 def textCompare(filename1,filename2):
 2     f1=open(filename1,'r')
 3     f2=open(filename2,'r')
 4     rownumber=0
 5     colnumber=0
 6     line1='hello'
 7     while line1!='':
 8         line1=f1.readline()
 9         line2=f2.readline()
10         if line1==line2:
11             rownumber+=1
12         else:
13             for char1 in line1:
14                 if char1==line2[colnumber:colnumber+1]:
15                     colnumber+=1
16                 else:
17                     print 'rownumber is ',rownumber+1,'colnumber is ',colnumber+1
18                     colnumber=0
19                     rownumber+=1
20                     break
21     f1.close()
22     f2.close()
23 
24 textCompare('gui.py','gui2.py'

9–7.   Parse the file. Win32 users: create a used to parse the Windows.Ini files. POSIX users: create a /etc/serves file parsing program. Other users: system configuration file to write an analysis of a particular structure of the program.

 1 def parseIni(filename):
 2     f=open(filename,'r')
 3     dict1={}
 4     for eachLine in f:
 5         index=eachLine.find('=');
 6         if index!=-1:
 7             key=eachLine[:index].strip()
 8             value=eachLine[index+1:].strip()
 9             dict1[key]=value
10     for key in dict1:
11         print key,'=',dict1[key]
12     f.close()
13 
14 parseIni('system.ini')

9–10 of family financial management. Create a family financial management procedures. Your program needs to handle savings, checking, financial market, the deposit and other accounts. Provide a menu operation interface for each account, to deposit, withdraw, borrowing, lending and other operations. In addition to providing a cancel option. The user logs out of the procedure related data should be saved to the file to (for backup purposes, the execution of the program is to backup.)

 1 # -*- coding: utf-8 -*-
 2 import shutil
 3 
 4 def showAccount():
 5      print '''
 6 Please choose your operating account: 
 7 (1)Savings
 8 (2)Check
 9 (3)Financial market
10 (4)Deposit
11 (5)Save and exit
12 (6)Exit without saving
13 (s)Check your balance'''
14      return raw_input('>')
15 
16 def showOperate():
17      print '''
18 Please choose what you want to do: 
19 (1)Deposit
20 (2)Teller
21 (3)Borrow
22 (4)Loan'''
23      return raw_input('>')
24 
25 def parseIni(filename):
26      f=open(filename,'r')
27      dict1={}
28      for eachLine in f:
29           index=eachLine.find('=');
30           if index!=-1:
31                key=eachLine[:index].strip()
32                value=int(eachLine[index+1:].strip())
33                dict1[key]=value
34      f.close()
35      return dict1
36 
37 def operate(a,k,o,m):
38      if o=='1':a[k]+=m;print 1
39      elif o=='2':a[k]-=m;print 2
40      elif o=='3':a[k]-=m;print 3
41      elif o=='4':a[k]+=m;print 4
42 
43 def save(account,filename):
44      f=open(filename,'w')
45      for k in account:
46           f.writelines('%s=%s\n'%(k,account[k]))
47      f.close()
48 
49 def showBalance():
50      for k in account:
51           print '%s = %s'%(k,account[k])
52      
53 
54 key=''
55 accNum=''
56 account=parseIni('account.txt')
57 
58 while True:
59      accNum = showAccount()
60      if accNum=='1' or accNum=='2' or accNum=='3' or accNum=='4':
61           opeNum = showOperate()
62           if opeNum=='1' or opeNum=='2' or opeNum=='3' or opeNum=='4':
63                money = int(raw_input('You have to input the amount of operation: '))
64                if accNum=='1':key='deposit'
65                elif accNum=='2':key='check'
66                elif accNum=='3':key='finance'
67                elif accNum=='4':key='regular'
68                operate(account,key,opeNum,money)
69                save(account,'account.txt')
70           else:print "Input error, please input again!"
71      elif accNum=='5':
72           save(account,'account.txt')
73           shutil.copy('account.txt','accountbak.txt')
74           break
75      elif accNum=='6':
76           shutil.copy('accountbak.txt','account.txt')
77           break
78      elif accNum=='s':
79           showBalance()
80      else:print "Input error, please input again!"

9–16.   Text processing. The width of the people enter the text often exceeds the screen. Write a program, line of text in a text file search length greater than 80 characters. From the most close to the 80 character word line breaks, the remaining files into the next line.

Program execution is completed, should be no more than 80 characters of text line.

 1 import shutil
 2 import os
 3 def formatText(filename):
 4     f=open(filename,'r')
 5     ftemp=open('temp.py','w')
 6     for eachLine in f:
 7         line=eachLine.strip('\n')
 8         row=len(line)/80
 9         if len(line)%80==0 and len(line)!=0:row-=1
10         for n in range(row+1):
11             ftemp.writelines(line[n*80:(n+1)*80]+'\n')    
12     f.close()
13     ftemp.close()
14     shutil.copy('temp.py',filename)
15     os.remove('temp.py')
16     
17 formatText('test.py')

 9–17 text processing. Create an original text file editor. Your program should be menu driven, are these options:

1) Create a file (file name and arbitrary line text input),

2) Display the file (the file contents to the screen),

3) To edit a file (input rows to be modified, and then allow the user to modify),

4) Save the file

5) Sign out.

 1 # -*- coding: GBK -*-
 2 import os
 3 
 4 def show_menu():
 5     print '''
 6 (1)Create a file
 7 (2)Display file
 8 (3)Edit the file
 9 (4)Save the file
10 (5)Sign out'''
11     return raw_input('>')
12 
13 def create_file():
14     ls = os.linesep
15     while True:  
16         fname = raw_input('Please input to create the file name: ') 
17         if os.path.exists(fname):  
18             print "Error:'%s'already exists" % fname  
19         else:  
20             break  
21     allline = []  
22     print "\N input: ('@@'exit input).\n"  
23     while True:  
24         entry = raw_input('> ')  
25         if entry=='@@':  
26             break  
27         else:
28             allline.append(entry)  
29     fobj = open(fname, 'w')  
30     fobj.writelines(['%s%s' % (x, ls) for x in allline])  
31     fobj.close()
32     return fname
33 
34 def show_content():
35     while True:  
36         fname = raw_input('Please enter to display the file name: ') 
37         if not os.path.exists(fname):  
38             print "Error:'%s'does not exist" % fname  
39         else:  
40             break
41     fobj=open(fname,'r')
42     i=1
43     for eachLine in fobj:
44         print i,eachLine,
45         i+=1
46     fobj.close()
47 
48 def edit_file(): 
49     while True:  
50         fname = raw_input('Please input you want to edit the file name: ') 
51         if not os.path.exists(fname):  
52             print "Error:'%s'does not exist" % fname  
53         else:  
54             break
55     fobj=open(fname,'r')
56     allline=fobj.readlines()
57     while True:
58         i=1
59         for eachLine in allline:
60             print i,eachLine,
61             i+=1
62         fline=raw_input("Please input the number you want to edit ('@@'exit edit): ")
63         if fline=='@@':break
64         fcontent=raw_input('Please input you want to replace the content: ')
65         allline[int(fline)-1]=fcontent+'\n'
66     fobj.close()
67     return (fname,allline)
68 
69 def save_file(fntemp,allline):
70     fobj=open(fntemp,'w')
71     for line in allline:
72         fobj.writelines(line)
73     fobj.close()
74         
75 
76 while True:
77     operat=show_menu()
78     if operat=='5':break
79     elif operat=='1':create_file()
80     elif operat=='2':show_content()
81     elif operat=='3':fntemp,allline=edit_file()
82     elif operat=='4':save_file(fntemp,allline)
83     else:
84         print 'Input error, please input again'

Posted by Fitch at November 28, 2013 - 1:31 PM