python从入门到实践 第十章习题(高级编程技术 week5-2)

python从入门到实践 第十章习题(高级编程技术 week5-2)

10.1 读取整个文件

  1. 注意with:关闭文件的实时机不容易确定,但通过with结构,可以让python去确定,这样我就只需要打开文件,python自己会在何合适的时候自动将其关闭
  2. 逐行读取:使用一个for对文件对象进行迭代。
  3. 注意空白行的问题,一般情况下都需要一个rstrip函数去除末尾空白字符。
  4. 将文件的各行存储到一个列表:readlines函数

10-1/2 python学习笔记

注意,读完文件后,便不能再次读取(因为缓冲区内的内容已被取完),因此不能三种读取文件的语句同时读取同样的内容。

file_path = './learrning_python.txt'
with open(file_path) as file_object:
    # t1 = file_object.read()
    # print(t1.rstrip())
    # for line in file_object:
        # print(line)
    t3 = file_object.readlines()

for line in t3:
    print(line)

for line in t3:
    print(line.replace('Python', 'C'))
    # line = line.replace('Python', 'C')
    # print(line)

# for line in t3:
    # print(line)

10.2 写入文件

注意w模式下,写入文件若已存在会自动清空文件。
a模式下,可以把写入到文件的行都添加到文件末尾。
还有,write不会在写入文件的时候自动加换行符。

10-4 访客名单

file_path = './guest_book.txt'

with open(file_path,'a') as file_object:
    while 1:
        name = input('Please enter your name here : ')
        file_object.write(name+'\n')
        flag = input('Do you want to quit? y/n')
        if flag.lower() == 'y':
            break

运行效果如图所示

10.3 异常

在书中的例子,介绍了这几种一场对象。

  1. ZeroDivisionError
  2. FileNotFoundError

我们可以使用try-expect语句告诉解释器该如何处理这些错误,当然也可以告诉解释器不要管这个错误,这可以使用一个pass语句来实现。

10-8/9

cat_file_path = './cats.txt'
dog_file_path = './dogs.txt'

try:
    with open(cat_file_path) as file_object:
        for line in file_object:
            print(line.strip())
except FileNotFoundError:
    print('Please put the file in ', cat_file_path)

try:
    with open(dog_file_path) as file_object:
        for line in file_object:
            print(line.strip())
except FileNotFoundError:
    # print('please put the file in ', dog_file_path)
    pass

在测试的时候,我创建了一个cats.txt,但是没有创建dogs.txt,运行结果如图所示:

在换成pass之后,程序能够忽略错误,不继续显示错误信息。

10-10

我从使用wget http://www.gutenberg.org/files/1342/1342-0.txt该命令从网络上下载了傲慢与偏见的文本文档,使用该程序处理后得出有8018个’the’。

file_path = './1342-0.txt'
with open(file_path) as file_object:
    str = ''
    for line in file_object:
        str += line.strip()
    print(str.lower().count('the'))

10.4 存储数据

这里介绍了json文件的存储。
json文件使用dump函数存储,使用load加载,都挺简单的。

10-11/12

这里我新添加了一个异常:json.decoder.JSONDecodeError
在文件存在但为空的时候就会触发这样的异常,因此仍然需要处理。

import json
file_path = './number.txt'
try:
    with open(file_path) as file_object:
        number = json.load(file_object)
        print('I know your favorite number ! It\'s ', number ,'.')
except  (json.decoder.JSONDecodeError, FileNotFoundError):
    number = input('Please enter your favorite number : ')
    with open(file_path, 'w') as file_object:
        json.dump(number, file_object)
    print('I will remember you !')

猜你喜欢

转载自blog.csdn.net/wyfwyf12321/article/details/79821184
今日推荐