3–10. 异常。
使用类似readTextFile.py 中异常处理的方法取代 readTextFile.py makeTextFile.py 中对os.path.exists() 的调用。反过来, 用os.path.exists() 取代readTextFile.py 中的异常处理方法。
# coding=utf-8
__author__ = 'Ibuki Suika'
'makeTextFile.py -- create text file'
import os
ls = os.linesep
# get filename
fileName = raw_input('filename: ')
while True:
try:
f = open(fileName, 'r')
except IOError:
break
else:
print('ERROR: %s already exists' % fileName)
fileName = raw_input('filename: ')
# get file content (text) lines
content = []
print "\nEnter lines ('.' by itself to quit).\n"
# loop until user terminates input
while True:
entry = raw_input('> ')
if entry == '.':
break
else:
content.append(entry)
# write lines to file with proper line-ending
try:
fobj = open(fileName, 'w')
except IOError as e:
print('file open error:%s' % e.message)
else:
fobj.writelines(['%s%s' % (x, ls) for x in content])
fobj.close()
print 'DONE!'
# coding=utf-8
__author__ = 'Ibuki Suika'
'readTextFile.py -- read and display text file'
import os
# get filename
fname = raw_input('Enter filename: ')
print
# attempt to open file for reading
if not os.path.exists(fname):
print "file not exists"
else:
fobj = open(fname, 'r')
for eachLine in fobj:
print eachLine,
fobj.close()
3–11.字符串格式化
不再抑制readTextFile.py 中 print 语句生成的 NEWLINE 字符,修改你的代码, 在显示一行之前删除每行末尾的空白。这样, 你就可以移除 print 语句末尾的逗号了。
提示: 使用字符串对象的 strip()方法
# coding=utf-8
__author__ = 'Ibuki Suika'
'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:
for eachLine in fobj:
print eachLine.strip()
fobj.close()
3–12. 合并源文件。
将两段程序合并成一个,给它起一个你喜欢的名字,比方readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。
# coding=utf-8
__author__ = 'Ibuki Suika'
import os
ls = os.linesep
def read_text_file():
fname = raw_input('Enter filename: ')
print
try:
fobj = open(fname, 'r')
except IOError, e:
print "*** file open error:", e
else:
for eachLine in fobj:
print eachLine.strip()
fobj.close()
def write_text_file():
fileName = raw_input('filename: ')
while True:
try:
f = open(fileName, 'r')
except IOError:
break
else:
print('ERROR: %s already exists' % fileName)
fileName = raw_input('filename: ')
content = []
print "\nEnter lines ('.' by itself to quit).\n"
while True:
entry = raw_input('> ')
if entry == '.':
break
else:
content.append(entry)
try:
fobj = open(fileName, 'w')
except IOError as e:
print('file open error:%s' % e.message)
else:
fobj.writelines(['%s%s' % (x, ls) for x in content])
fobj.close()
print 'DONE!'
def menu():
print('1. Read File')
print('2. Write File')
print('3. Exit')
choose = input('>')
return choose
if __name__ == '__main__':
choose = menu()
if choose == 1:
read_text_file()
elif choose == 2:
write_text_file()