python-文件和异常
1、从文件中读取数据
要使用文本文件中的信息,首先需要将信息读取到内存中。为此,你可以一次性读取文件的全部内容,也可以以每次一行的方式逐步读取
1.1、读取整个文件
with open('pi_digits.txt') as file_object:
contents=file_object.read()
print(contents)
函数open()返回一个表示文件的对象,python将这个对象存储在我们将在后面使用的变量中
关键字with在不再需要访问文件后将其关闭。——使用这个结构,可让python去确定:你只管打开文件,并在需要时使用它,python自会在合适的时候自动将其关闭
1.2、逐行读取
file_name='pi_digits.txt'
with open(file_name) as file_object:
for line in file_object:
print(line)
1.3、创建一个包含文件各行内容的列表
file_name='pi_digits.txt'
with open(file_name) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
2、写入文件
2.1、写入空文件
file_name='programming.txt'
with open(file_name,'w') as file_object:
file_object.write("I love programming")
调用函数open()时提供了两个实参,第一个实参也是要打开的文件的名称,第二个实参(‘w’)告诉python,我们要以写入模式打开这个文件
读取模式 r
写入模式 w
附加模式 a
读取和写入文件模式 r+
2.2、附加到文件
file_name='programming.txt'
with open(file_name,'a') as file_object:
file_object.write("I also love creating new games")
3、异常
3.1、处理ZeroDivisionError异常,使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
3.2、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("\nSecond number:")
if second_number=='q'
break
try:
answer=int(first_number)/int(second_number)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(answer)
3.3、失败时一声不吭
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)
pass
else:
words=contents.split()
num_words=len(words)
print("The file "+filename+"has about "+str(num_words)+"words.")
filenames=['alice.txt','siddhartha.txt','mody_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
pass语句,可在代码块中让python什么都不做
4、存储数据
模块json让你能够将简单的python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
4.1、使用json.dump()和json.load()
json.dump()用来存储数字,接受两个参数:要存储的数据以及可用于存储数据的文件对象
json.load()用来将这些数字读取到内存中的程序内。
number_writer.py
import json
numbers=[2,3,5,7,11,13]
filename='numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object)
number_reader.py
import json
filename='numbers.json'
with open(filename) as file_object:
numbers=json.load(file_object)
print(numbers)
我们使用json.load()加载存储在numbers.json中的信息,并将其存储在变量numbers中

浙公网安备 33010602011771号