一个python读写文件脚本,代码如下:
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