转:《Python核心编程》第二版第三…

好毅力的原作者!赞~

下面的问题涉及了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'


3-10.
异常。使用类似readTextFile.py中异常处理的方法取代makeTextFile.py中对os.path.exists()的调用。反过来,用os.path.exists()取代readTextFile.py中的异常处理方法。
【答案】
代码如下:
def makeTextFile():

    import os
    ls = os.linesep
    
    # get filename
    while True:
        fname = raw_input('Enter file name: ')
        try:
            open(fname, 'r')
            print" *** ERROR: '%s' already exists" % fname
        except IOError:
            break
            fname.close()

    
    # 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])
    fobj.close()
    print 'Done'

def readTextFile():

    # get filename
    fname = raw_input('Enter filename: ')
    
    import os
    
    if os.path.exists(fname): 
        fobj = open(fname, 'r')
        for eachLine in fobj:
            print eachLine,
        fobj.close()   
    else:
        print 'Can not find this file!'

print "'m' means make a new text file."
print "'r' means read a text file."
choice = raw_input('Please input your choice ... ')
if choice == 'm': makeTextFile()
elif choice == 'r': readTextFile()
else: print'end'

 

3-11.
字符串格式化。不再抑制readTextFile.py中print语句生成的NEWLINE字符,修改你的代码,在显示一行之前删除每行末尾的空白。这样,你就可以移除print语句末尾的逗号了。提示:使用字符串对象的strip()方法。
【答案】
代码如下:
# get filename
fname = raw_input('Enter file name: ')

# 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.rstrip()
    fobj.close()

 

3-12.
合并源文件。将两段程序合并成一个,给它起一个你喜欢的名字,比如readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。
【答案】
代码如下:
def makeTextFile():

    import os
    ls = os.linesep
    
    # 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 proper line-ending
    fobj = open(fname, 'w')
    fobj.writelines(['%s%s' % (x,ls) for x in all])
    fobj.close()
    print 'Done'

def readTextFile():

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

print "'m' means make a new text file."
print "'r' means read a text file."
choice = raw_input('Please input your choice ... ')
if choice == 'm': makeTextFile()
elif choice == 'r': readTextFile()
else: print'end'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值