下面的問題涉及了makeTextFile.py和readTextFile.py指令碼。
【注】網路上找到的makeTextFile.py和readTextFile.py原始碼,和原書例子稍有區別。
'makeTextFile.py -- create text file'
import os
# get filename
while True:
fname = raw_input('Enter file name: ')
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:
entry = raw_input('> ')
if entry == '.':
break
else:
all.append(entry)
# write lines to file with NEWLINE line terminator
fobj = open(fname, 'w')
fobj.write('\n'.join(all))
fobj.close()
print 'DONE!'
'readTextFile.py -- read and display text file'
# get filename
fname = raw_input('Enter file name: ')
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()
3-8.
Python代碼。將指令碼拷貝到你的檔案系統中,然後修改它。可以添加註釋,修改提示符(‘>’太單調了)等,修改這些代碼,使他們看上去更舒服。
【答案】
略。
3-9.
移植。如果你在不同類型的電腦系統中分別安裝有Python,檢查一下,os.linesep的值是否有不同。記下作業系統的類型及linesep的值。
【答案】
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\root>python
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>>
在一個linux作業系統中
[GCC 4.1.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\n'