10.文件和异常
从文件中读取数据
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
关键字 with 在不再需要访问文件后将其关闭。在这个程序中,注意到我们调用了 open(),但没有调用 close();你也可以调用 open()和 close()来打开和关闭文件,但这样做时,如果程序存在 bug,导致 close()语句未执行,文件将不会关闭。这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早地调用 close(),你会发现需要使用文件时它已关闭(无法访问),这会导致更多的错误。并非在任何情况下都能轻松确定关闭文件的恰当时机,但通过使用前面所示的结构,可让 Python 去确定:你只管打开文件,并在需要时使用它,Python 自会在合适的时候自动将其关闭。
逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
open()返回的文件对象只在 with 代码块内可用。如果要在 with 代码块外访问文件的内容,可在 with 代码块内将文件的各行存储在一个列表中,并在 with 代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。
写入文件
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.\n")
file_object.write("I love creating new games.\n")
打开文件时可指定读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')。如果你省略了模式实参,Python 将以默认的只读模式打开文件。
异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
else 代码块
print("Give me two numbers, 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("Second 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)
处理 FileNotFoundError 异常
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
失败时一声不吭
def count_words(filename):
try:
--snip--
except FileNotFoundError:
pass
else:
--snip--
存储数据
使用 json.dump() 和 json.load()
# 注意文件名不要用 json.py
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)