Python编程核心之makeTextFile.py和readTextFile.py

时间:2023-12-21 11:19:08

引言:

  最近大半年都在学习python编程,在双十一的时候购买了《Python编程核心》,看到makeTextFile.py和readTextFile.py两个例子有点错误,所以在这里给修正一下!

makeTextFile.py脚本:

#!/usr/bin/env python
#_*_coding:utf8_*_ 'makeTextFile.py -- create text file' import os ls = os.linesep #get filename
while True:
#需要添加的语句,并且需要缩进,后面的四条语句也需要缩进
fname = raw_input("please input file name:\n")
if os.path.exists(fname):
print "ERROR: '%s' already exists" % fname
else:
break
#get file content (text) Lines
all_list = []
"""原著上使用了all做list,但是在使用eclipse是发现有assignment to reserved built-in symbol:all的warning,所以就使用all_list"""
#all = []
print "\nEnter lines ('.' by itself to quit).\n" #loop until user terminates input
while True:
entry = raw_input('> ')
if entry == '.':
break
else:
all_list.append(entry)
#write lines to file with proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls) for x in all_list])
fobj.close()
print 'DONE!'

readTextFile.py脚本:

#!/usr/bin/env python
#_*_coding:utf8_*_ 'readTextFile.py -- read and display text file'
#from makeTextFile import fobj #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:
#display contents to the screen
for eachLine in fobj:
print eachLine,
fobj.close()