用户输入一个尚不存在的文件名,然后输入文件的每一行,最后将所有内容写入文本文件。
import os
ls=os.linesep
#get filename
fname=raw_input('input filename:\n')
if os.path.exists(fname):
print "ERROR:'%s' already exists" % fname
else:
all=[]
print"\n Enter lines('.' to quit)\n"
#loop until user terminates input
while True:
entry=raw_input('>')
if entry=='.':
break
else:
all.append(entry)
#write lines to file with proper line-ending
fout=open(fname,'w')
fout.writelines(['%s%s' %(x,ls) for x in all])
fout.close()
print 'DONE!'
程序结果:
import os
#get filename
fname=raw_input('input filename:\n')
print
try:
fin=open(fname,'r')
except IOError,e:
print "file open error:",e
else:
for eachline in fin:
print eachline,
fin.close()
程序运行如下: