创建文件(makeTextFile.py)脚本提醒用户输入一个尚不存在的文件名,然后由用户输入文件每一行,最后将所有文本写入文本文件
#!/usr/bin/env python 'makeTextFile.py -- creat text file' import os
ls = os.linesep # get file name
while True:
if os.path.exists(fname): #不存在返False,存在返True
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:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry) #write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x,ls) for x in all])
#列表解析,将列表中每行(每个元素)都写入文件,两个%s分别是字符串和每行结束符
fobj.close
print 'DONE!'
文件读取和显示(readTextFile.py)
#!/user/bin/env python 'readTextFile.py -- read and display text file' # get filename
fname = raw_input('Enter filename')
print #隔开提示和文本
# attempt to open file for reading
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:",e
else:
# dispaly content to the screen
for eachLine in fobj
print eachLine,
fobj.close()