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()