python核心编程课后题第二版36页第二章

下面的问题涉及了makeTextFile.py和readTextFile.py脚本。

3-8 python代码。将脚本拷贝到你的文件系统中,然后修改他。可以添加注释,修改提示符(“>”太单调了)等,修改这些代码,使它看上去更舒服。

关于makeTextFile.py的源代码如下:

#coding=utf-8
'makeTextFile.py -- create text file'

import os
ls = os.linesep
while 1:
    fname = raw_input('Enter file name:')
    if os.path.exists(fname):
        print "*** ERROR: '%s' already exists" % fname
    else:
        break

all = []
print '\nEnter lines ("." by itself to quit).\n'

while 1:
    entry = raw_input('>>')
    if entry == '.':
        break
    else:
        all.append(entry)

fobj = open(fname, 'w')
fobj.write('\n'.join(all))
fobj.close()
print 'Done!'

注:对书本上源代码做了少量修改。书本上也缺少了fname的定义,这里已经补充。

下面是做了详细注释后的代码:

#coding=utf-8
'makeTextFile.py -- create text file'

import os #导入os模块
ls = os.linesep #os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。这里直接定义为ls
while 1:
    fname = raw_input('Enter file name:') #输入文件名称
    if os.path.exists(fname): #使用os.path.exist()判断,如果存在则提示错误
        print "*** ERROR: '%s' already exists" % fname
    else:
        break #如果不存在就退出循环,继续执行

all = [] #定义空列表
print '\nEnter lines ("." by itself to quit).\n' 

while 1:
    entry = raw_input('>>') #输入一行代码
    if entry == '.': #判断,如果是.就退出while循环
        break
    else: #如果不是.则保存入all中
        all.append(entry) #使用append添加在列表中


fobj = open(fname, 'w') #打开fname文件,写入模式
fobj.write('\n'.join(all)) #使用\n连接all中每个值
fobj.close() #关闭文件
print 'Done!' #ok!

关于makeTextFile.py的代码如下:

#coding=utf-8
'readTextFile.py -- read and display text file'

fname = raw_input('Enter file name:')
print 

try:
    fobj = open(fname, 'r')
except IOError, e:
    print '*** file open error: ', e
else:
    for eachline in fobj:
        print eachline,
    fobj.close()

注:也经过了轻微的调整,比如eachLine改成了eachline。下面是添加注释后的代码:

#coding=utf-8
'readTextFile.py -- read and display text file' #模块说明

fname = raw_input('Enter file name:') #输入文件名称
print #打印一个空行,做分割用

try: #尝试一下,如果打开就成功了
    fobj = open(fname, 'r')
except IOError, e: #如果不成功即输出错误信息
    print '*** file open error: ', e
else: #如果成功就执行下列代码
    for eachline in fobj: #书中第31页对此类循环做了说明:我们一次读入文件的所有行,然后关闭文件,再迭代每一行输出。这样写代码的好处是能够快速完整的访问文件。内容输出和文件访问不必交替进行。这样代码更清晰而且将不相关的任务区分开来。
        print eachline,#31页同样有这句的说明:因为文件中每行文本已经自带了换行字符,如果我们不抑制print语句产生的换行符,文本在显示时就会有额外的空行产生。
    fobj.close()

3-9 移植。如果你在不同类型的计算机系统中分别安装有python,检查一下,os.linesep的值是否有不同,记下操作系统的类型及linesep的值。

注:并没有亲身测试,下面是百度知道中找到的答案:

os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。(原文连接:http://zhidao.baidu.com/question/310965461.html)

3-10 异常。使用类似readTextFile.py中异常处理的方法取代readTextFile.py makeTextFile.py中对os.path.exists()的调用。反过来,用os.path.exists()取代readTextFile.py中的异常处理方法。

修改后的makeTextFile.py:

#coding=utf-8
'makeTextFile.py -- create text file'

while 1:
    fname = raw_input('Enter file name:')
    try: #尝试打开文件
        open(fname)
    except: #如果失败说明文件不存在,可以退出while循环
        break
    else: #如果能打开说明文件存在,继续输入
        print '%s is used by other file.' % fname

all = []
print '\nEnter lines ("." by itself to quit).\n'

while 1:
    entry = raw_input('>>')
    if entry == '.':
        break
    else:
        all.append(entry)

fobj = open(fname, 'w')
fobj.write('\n'.join(all))
fobj.close()
print 'Done!'

修改后的readTextFile.py代码如下:

#coding=utf-8
import os
'readTextFile.py -- read and display text file'

while 1:
    fname = raw_input('Enter file name:')
    if os.path.exists(fname): #判断文件是否存在,如果存在就退出循环,说明可以打开
        break
    else: #如果不存在需要继续输入
        print 'The file %s do not exist.' % fname

fobj = open(fname)
for eachline in fobj:
    print eachline,
fobj.close()

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

#coding=utf-8
import os
'readTextFile.py -- read and display text file'

while 1:
    fname = raw_input('Enter file name:')
    if os.path.exists(fname):
        break
    else:
        print 'The file %s do not exist.' % fname

fobj = open(fname)
for eachline in fobj:
    eachline = eachline.rstrip() #rstrip表示去掉右侧的空格或换行,strip表示去掉两端的空格或换行,lstrip表示去掉左侧的空格或换行。
    print eachline
fobj.close()

3-12 合并源文件。将两段代码合并成一个,给它起一个你喜欢的名字。比如readNwriteTextFiles.py。让用户自己选择是创建还是显示一个文本文件。

#coding=utf-8
import os

def writeFile():
    while 1:
        fname = raw_input('Enter file name:')
        try: #尝试打开文件
            open(fname)
        except: #如果失败说明文件不存在,可以退出while循环
            break
        else: #如果能打开说明文件存在,继续输入
            print '%s is used by other file.' % fname

    all = []
    print '\nEnter lines ("." by itself to quit).\n'

    while 1:
        entry = raw_input('>>')
        if entry == '.':
            break
        else:
            all.append(entry)

    fobj = open(fname, 'w')
    fobj.write('\n'.join(all))
    fobj.close()
    print 'Done!'

def readFile():
    'readTextFile.py -- read and display text file'

    while 1:
        fname = raw_input('Enter file name:')
        if os.path.exists(fname):
            break
        else:
            print 'The file %s do not exist.' % fname

    fobj = open(fname)
    for eachline in fobj:
        eachline = eachline.rstrip()
        print eachline
    fobj.close()
if __name__ == '__main__':
    print 'There are 2 chooses: 1> write file. 2> read file.'
    choose = raw_input('Enter your choose>>')
    if choose == '1':
        writeFile()
    elif choose == '2':
        readFile()
    else:
        print 'Enter error.'
原文地址:https://www.cnblogs.com/alexkh/p/2802294.html