《Python核心编程》第3章 Python基础 练习

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



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值