第10章 文件和异常
处理异常和文件,你在本章学习的技能可提高程序的适用性、可用性和稳定性。
10.1 从文件中读取数据
关键字with在不再需要访问文件后将其关闭。
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
相对文件路径:
with open('text_files\pi_digits.txt') as file_object:
绝对文件路径:
file_path='C:\users\other\text_files\pi_digits.txt'
with open(file_path) as file_object:
逐行读取:
with open(filename) as file_object:
for line in file_object:
print(line)
创建一个包含文件各行内容的列表:
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
10.2 写入文件
写入空文件:
filename='programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming.")
动手试一试:
#10-3
name=input("Please enter your name:")
if name:
filename='guest.txt'
with open(filename,'a') as file_object:
file_object.write(name+'\n')
#10-4
name=""
while name != 'quit':
name=input("Please enter your name:")
if name != 'quit':
print("Hello,"+name)
filename='guest_book.txt'
with open(filename,'a') as file_object:
file_object.write(name+' has visited.\n')
10.3 异常
如果你编写了处理该异常的代码,程序将继续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
1、处理zerodivisionerror异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
通过预测可能发生错误的代码,可编写健壮的程序,它们即使面临无效数据或缺少资源,也能继续运行,从而能够抵御无意的用户错误和恶意的攻击。
处理FileNotFoundError异常:
def count_words(filename):
try:
with open(filename) as f_obj:
contents=f_obj.read()
except FileNotFoundError:
msg="Sorry,the file "+filename+" does not exist."
print(msg)
else:
words=contents.split()
num_words=len(words)
print("The file "+filename +
" has about "+str(num_words)+" words.")
filename='guest_book.txt'
count_words(filename)
编写的很好且经过详尽测试的代码不容易出现内部错误,如语法或逻辑错误,但只要程序依赖于外部因素,如用户输入、存在指定的文件、有网络连接,就有可能出现异常。凭借经验可判断该在程序的什么地方包含异常处理块,以及出现错误时该向用户提供多少相关的信息。
10.4 存储数据
使用json.dump()和json.load()
numbers=[2,3,5,7,11,13]
filename='numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
filename='numbers.json'
with open(filename) as f_obj:
numbers_=json.load(f_obj)
print(numbers_)
网友评论