昨日知识点回顾
从模块中导入类/模块
今日知识点学习
第十章 文件和异常
10.1 从文件中读取数据
10.1.1 读取整个文件
txt文件与程序文件在同一级目录
python">with open('pi_digits.txt') as file_object:contents = file_object.read()
print(contents)# 运行结果:
# 3.1415926535
# 8979323846
#
10.1.2 文件路径
python">with open('文件路径/Desktop/pi_digits.txt') as file_object:contents = file_object.read()
print(contents.rstrip())
# print(contents)# 运行结果:
# 3.1415926535
# 8979323846
# 2643383279
10.1.3 逐行读取
python">filename = 'pi_digits.txt'
with open(filename) as file_object:for line in file_object:print(line.rstrip())# 运行结果:
# 3.1415926535
# 8979323846
10.1.4 创建一个包含文件各行内容的列表
python">filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()print(lines)
for line in lines:print(line.rstrip())# 运行结果:
# ['3.1415926535\n', ' 8979323846']
# 3.1415926535
# 8979323846
10.1.5 使用文件的内容
python">filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()pi_string = ''
for line in lines:# pi_string += line.rstrip()pi_string += line.strip()print(pi_string)
print(len(pi_string))# 运行结果:
# 3.14159265358979323846
# 22
10.1.6 包含一百万位的大型文件
python">filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()pi_string = ''
for line in lines:pi_string += line.strip()birthday = input("Enter your birthday")
if birthday in pi_string:print("Your birthday appears in the first million digits of pi!")
else:print("Your birthday does not appear in the first million digits of pi!")
print(f"{pi_string[:52]}...")
print(len(pi_string))# 运行结果:
# Enter your birthday120372
# Your birthday does not appear in the first million digits of pi!
# 3.14159265358979323846264338327950288419716939937510...
# 6554
10.2 写入文件
10.2.1 写入空文件
python">filename = 'programming.txt'
with open(filename, 'w', encoding='UTF-8') as file_object:file_object.write("I love programming.\n")
10.2.2 写入多行
python">filename = 'programming.txt'
with open(filename, 'w', encoding='UTF-8') as file_object:file_object.write("I love programming.\n")file_object.write("I love creating new games.\n")
10.2.3 附加到文件
python">filename = 'programming.txt'
with open(filename, 'w', encoding='UTF-8') as file_object:"""写入多行"""file_object.write("I love programming.\n")file_object.write("I love creating new games.\n")with open(filename, 'a') as file_object:"""附加到文件"""file_object.write("I also love finding meaning in large datasters.\n")file_object.write("I love creating apps that can run in a browser.\n")with open(filename) as file_object:"""打印文件内容"""contents = file_object.read()print(contents)# 运行结果:
# I love programming.
# I love creating new games.
# I also love finding meaning in large datasters.
# I love creating apps that can run in a browser.
10.3 异常
10.3.1 处理ZeroDivisionError异常
python">print(5/0)# 运行结果:
# ZeroDivisionError: division by zero
10.3.2 使用try-except代码块
python">try:print(5 / 0)
except:print("你不能除0运算")# 运行结果:
# 你不能除0运算
10.3.3 使用异常避免崩溃
python">print("给我两个数,我来做除法")
print("按q结束程序")while True:first_number = input('\n请输入第一个数:')if first_number == 'q':breaksecond_number = input("请输入第二个数:")if second_number == 'q':breakanswer = int(first_number)/int(second_number)print(answer)# 运行结果:
# 给我两个数,我来做除法
# 按q结束程序
#
# 请输入第一个数:5
# 请输入第二个数:0
# ZeroDivisionError: division by zero
10.3.4 else代码块
python">print("给我两个数,我来做除法")
print("按q结束程序")while True:first_number = input('\n请输入第一个数:')if first_number == 'q':breaksecond_number = input("请输入第二个数:")if second_number == 'q':breaktry:answer = int(first_number)/int(second_number)except ZeroDivisionError:print("第二个数不能为0")else:print(answer)# 运行结果:
# 给我两个数,我来做除法
# 按q结束程序
#
# 请输入第一个数:5
# 请输入第二个数:0
# 第二个数不能为0
#
# 请输入第一个数:2
# 请输入第二个数:4
# 0.5
#
# 请输入第一个数:q
#
# 进程已结束,退出代码0
10.3.5 处理FileNotFoundError异常
python">filename = "Alice.txt"
with open(filename,encoding='UTF-8') as f:contents = f.read()# 运行结果:
# FileNotFoundError: [Errno 2] No such file or directory: 'Alice.txt'
10.3.6 分析文本
python">filename = "programming.txt"
try:with open(filename, encoding='UTF-8') as f:contents = f.read()
except:print(f'抱歉,名为{filename}的文档不存在')
else:
# 计算文档中含有多少个单词print(f"{filename}中的内容:")print(contents)words = contents.split()num_words = len(words)print(f"{filename}中有{num_words}个单词")# 运行结果:
# programming.txt中的内容:
# I love programming.
# I love creating new games.
# I also love finding meaning in large datasters.
# I love creating apps that can run in a browser.
#
# programming.txt中有26个单词
10.3.7 使用多个文件
python">def count_words(filename):"""计算一个文件中包含多少个单词"""try:with open(filename, encoding='UTF-8') as f:contents = f.read()except:print(f'抱歉,名为{filename}的文档不存在')else:print(f"{filename}中的内容:")print(f"{contents[:200]}...")words = contents.split()num_words = len(words)print(f"{filename}中有{num_words}个单词")# filename = 'programming.txt'
# count_words(filename)filenames = ['programming.txt', 'pi_digits.txt', 'Alice.txt']
for filename in filenames:count_words(filename)# 运行结果:
# programming.txt中的内容:
# I love programming.
# I love creating new games.
# I also love finding meaning in large datasters.
# I love creating apps that can run in a browser.
# ...
# programming.txt中有26个单词
# pi_digits.txt中的内容:
# 3.14159265358979
# 3238462643383279
# 5028841971693993
# 7510582097494459
# 2307816406286208
# 9986280348253421
# 17067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954...
# pi_digits.txt中有9个单词
# 抱歉,名为Alice.txt的文档不存在
#
# 进程已结束,退出代码0
10.3.8 静默失败
pass语句不输出异常报告
python">def count_words(filename):"""计算一个文件中包含多少个单词"""try:with open(filename, encoding='UTF-8') as f:contents = f.read()except FileNotFoundError:passelse:print(f"{filename}中的内容:")print(f"{contents[:200]}...")words = contents.split()num_words = len(words)print(f"{filename}中有{num_words}个单词")# filename = 'programming.txt'
# count_words(filename)filenames = ['programming.txt', 'pi_digits.txt', 'Alice.txt']
for filename in filenames:count_words(filename)# 运行结果:
# programming.txt中的内容:
# I love programming.
# I love creating new games.
# I also love finding meaning in large datasters.
# I love creating apps that can run in a browser.
# ...
# programming.txt中有26个单词
# pi_digits.txt中的内容:
# 3.14159265358979
# 3238462643383279
# 5028841971693993
# 7510582097494459
# 2307816406286208
# 9986280348253421
# 17067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954...
# pi_digits.txt中有9个单词