一边学习python,一边练习python。这是一个好的学习方法。
下面这个脚本是根据课后题写的,吸收了别人的一些经验。只是一个很简单的脚本,大牛勿笑。
- ################################
- # Author : netcat #
- # QQ : 297020555 #
- # Date : 2012-1-3 #
- # Version : 1.0 #
- # Function: to read&write file #
- ################################
- import os
- ls=os.linesep
- numlist=['1','2','3']
- def getnum():
- input=raw_input('''
- ---------------------
- 1.read
- 2.write
- 3.quit
- ---------------------
- enter your select num:\n''')
- if input in numlist:
- return input
- else:
- print 'enter error,input again'
- return getnum()
- def getfile():
- file=raw_input('enter filename:\n')
- return file
- def comment():
- print 'enter "quit" to exit'
- lines=[]
- line=raw_input('>')
- while True:
- if line=='quit':
- return lines
- else:
- lines.append(line)
- line=raw_input('>')
- def write():
- if os.path.exists(file):
- f=open(file,'a')
- f.writelines(['%s%s'%(x,ls) for x in com])
- f.close()
- print 'append done'
- else:
- f=open(file,'w')
- f.writelines(['%s%s'%(x,ls) for x in com])
- f.close()
- print 'write done'
- def read():
- if os.path.exists(file):
- f=open(file,'r')
- for line in f:
- print line,
- else:
- print 'file is not exists'
- while True:
- num=getnum()
- if num=='1':
- file=getfile()
- read()
- elif num=='2':
- file=getfile()
- com=comment()
- write()
- else:
- print 'exit'
- break
转载于:https://blog.51cto.com/297020555/757403