【随手写程序】之phython 入门 读写文件程序
学习教程python核心编程第二版
课后练习之改写读写程序
import os
#line breaks is Common Var
ls=os.linesep
#define writing function
def writefile():
while True:
filename=raw_input("enter filename>")
if(os.path.exists(filename)):
print "%s,this file name is exists"
else:
break
all=[]
print "\n enter lines('.' by itself to quit).\n"
while True:
entry=raw_input('>')
if entry=='.':
break
else:
all.append(entry)
fobj=open(filename,'w')
fobj.writelines('%s%s'%(x,ls) for x in all)
fobj.close()
print 'done!'
#define reading function
def readfile():
while True:
filename=raw_input('enter a exist filename:')
if os.path.exists(filename):
print 'file exist'
break
else:
print 'file is no exist'
try:
fobj=open(filename,'r')
for eachline in fobj:
print eachline
fobj.close()
except IOError,e:
print 'file open error%s',e
wait=raw_input('wait')
#program start
print'''enter operation method :
1.\'n\' or \'N\' is represent new file
2.\'o\' OR \'O\' is represent open file'''
while True:
operStr=raw_input('enter oper>')
if(operStr=='o' or operStr=='O'):
readfile()
break
elif(operStr=='n' or 'N'==operStr):
writefile()
break
else:
print 'pelase input operation method'