一边学习python,一边练习python。这是一个好的学习方法。

下面这个脚本是根据课后题写的,吸收了别人的一些经验。只是一个很简单的脚本,大牛勿笑。

 

 
  
  1. ################################  
  2. #  Author :   netcat           #  
  3. #    QQ   :   297020555        #  
  4. #   Date  :   2012-1-3         #  
  5. # Version :   1.0              #  
  6. # Function: to read&write file #  
  7. ################################  
  8.  
  9. import os  
  10. ls=os.linesep  
  11.  
  12. numlist=['1','2','3']  
  13. def getnum():  
  14.     input=raw_input('''  
  15. ---------------------  
  16.         1.read  
  17.         2.write  
  18.         3.quit  
  19. ---------------------  
  20. enter your select num:\n''')  
  21.     if input in numlist:  
  22.         return input  
  23.     else:  
  24.         print 'enter error,input again'  
  25.         return getnum()  
  26.  
  27. def getfile():  
  28.     file=raw_input('enter filename:\n')  
  29.     return file  
  30.  
  31. def comment():  
  32.     print 'enter "quit" to exit'  
  33.     lines=[]  
  34.     line=raw_input('>')  
  35.     while True:  
  36.         if line=='quit':  
  37.             return lines  
  38.         else:  
  39.             lines.append(line)  
  40.             line=raw_input('>')  
  41.  
  42. def write():  
  43.     if os.path.exists(file):  
  44.         f=open(file,'a')  
  45.         f.writelines(['%s%s'%(x,ls) for x in com])  
  46.         f.close()  
  47.         print 'append done'  
  48.     else:  
  49.         f=open(file,'w')  
  50.         f.writelines(['%s%s'%(x,ls) for x in com])  
  51.         f.close()  
  52.         print 'write done'  
  53.  
  54. def read():  
  55.     if os.path.exists(file):  
  56.         f=open(file,'r')  
  57.         for line in f:  
  58.             print line,  
  59.     else:  
  60.         print 'file is not exists'  
  61.  
  62.  
  63. while True:  
  64.     num=getnum()  
  65.     if num=='1':  
  66.         file=getfile()  
  67.         read()  
  68.     elif num=='2':  
  69.         file=getfile()  
  70.         com=comment()  
  71.         write()  
  72.     else:  
  73.         print 'exit'  
  74.         break  
  75.  
  76.