第10章 文件和异常

2021-04-22  本文已影响0人  lkj666

参考书籍:《Python编程 从入门到实践》

1. 从文件中读取数据

1.1 一次性读取文件全部内容

#file_reader.py
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
  1. 无论以何种方式使用文件,第一步都是先打开文件。
  2. 方法read()可读取文件的全部内容。
  3. read()在读取到文件末尾时会返回一个空字符串,表现为一个空行,可用rstrip()去除。
  4. 程序会在*.py程序文件所在目录查找相应的文件,也可以使用路径标明位置。

1.2 逐行读取文件内容

#file_reader.py
filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrips)

1.3 在with代码块以外访问文件内容

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file.object.readlines()

for line in lines:
    print(line.rstrip())
  1. 将文件各行存储在一个列表中。
  2. 方法readlines():将文件中读取每一行,并将其存储在一个列表中。

1.4 使用文件的内容

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file.object.readlines()

pi_string = ''
for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))
  1. strip():去除字符串前后空白。
  2. len():计算字符串长度。
  3. 读取的文件,所有文本都默认为字符串。若要将其当作数字使用,需要用函数int()float()转换为整数或浮点数。



2. 写入文件

#write_message.py
filename = 'programming'

with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")
  1. open()函数接两个参数,第一个提供要打开的文件名称;第二提供模式。
  2. w:写入模式
    r:读取模式(默认是只读文件)
    a:附加模式
    r+:读取和写入模式
  3. 若文件不存在,Python会自动创建文件。
  4. Python只能将字符串写入文本文件,要写入数值,需要用str()将数字转换为字符串。



3. 异常

3.1 处理ZeroDivisionError异常

print("Give me two numers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("\nSecond number: ")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)
  1. try-except代码块,当执行try代码块出错时,执行except代码块。
  2. except代码块中,可以用pass告诉程序,即使程序出错,也可以什么都不显示。
  3. else代码块中,try代码块成功执行时,才会执行。

3.2 处理FileNotFoundError异常

def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = j_obj.read()
    except FileNotFoundError:
        msg = "Sorry, the file " + filename +" does not exist."
        print(msg)
    else:
        #计算文件大致包含多少个单词
        words = contents.spllit()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")

filename = 'alice.txt'
count_words(filename)

filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
  1. 方法split()以空格为分隔符将字符串分拆成多个部分,并将这些部分存储在一个列表中。



4. 存储数据

4.1 保存和读取用户生成的数据

import json

filename = 'username.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("What is your name?")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("we'll remember you when you comm back, " + username + "!")
else:
    print("Welcome back, " + username + "!")

json.dump()json.load()用于存储和加载数据对象。
json.dump()接两个参数:要存储的数据+可用于存储数据的文件对象。

4.1 重构程序

import json

def get_stored_useranme():
    """如果存储了用户名,就获取它"""
    filename = 'username.json'
    try:
        with open(filenam) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def greet_user():
    """问候用户,并指出起名字"""
    username = get_stored_username()
    if username:
        print("Welcom back, " + username + "!")
    else:
        username = input("What is your name?")
        filename = 'username.json'
        with open(username, 'w') as f_obj:
            json.dump(username, f_obj)
            print("We'll remember you when you come back, " + username + "!")

greet_user()

程序重构的目的是让逻辑更加清晰,每个函数都执行一个任务

上一篇 下一篇

猜你喜欢

热点阅读