python 学习源码练习(2)——简单文件读取
2017-11-27 21:55 逍楚客 阅读(336) 评论(0) 编辑 收藏 举报#文件创建
#!/usr/bin/python3
'makeTextFile.py--create text file'
import os
ls = os.linesep
#get filename
fname = input('please enter the filename:')
while True:
if os.path.exists(fname):
print ( "Error : '%s' already exists" % fname)
else:
break
#get file content(text) lines
all = []
print ("\nEnter Lines('.' by itself to quit).\n")
#loop until user terminates input
while True:
entery = input('>')
if entery == '.':
break
else:
all.append(entery)
#wirte lines in file
fobj = open(fname, 'w')
fobj.writelines(['%s%s' %(x, ls) for x in all])
fobj.close()
print ('Done!')
#read file and output to the screen
#!/usr/bin/python3
'readTextFile.py--read and display text file'
#get file name
fname = input('please input the file to read:')
try:
fobj = open(fname,'r')
except:
print("*** file open error" ,e)
else:
#display the contents of the file to the screen.
for eachline in fobj:
print(eachline,)
fobj.close()