"""文件路径"""
# 相对文件路径(适用于打开位于不同文件夹的文件)
with open(r'1\temp.py') as file_object:
# 运用方法read读取整个文件
contents = file_object.read()
print(contents.strip(), end='')
# 绝对文件路径(完整路径,任何位置,较麻烦)
file_path = r'C:\Users\user\Desktop\pi_digits.txt'
with open(file_path) as file_object:
contents = file_object.read()
print(contents.strip(), end='')
# 以每次一行的方式检查(遍历)文件
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip())
# 创建包含文件各行内容的列表,便于在with之外使用文件内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
# 方法readlines()从文件中读取每一行,并将其存储在一个列表中
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
"""文件处理"""
filename = 'guest.txt'
"""
默认(只读模式),
'r'(读取), 'w'(写入)->会覆盖原有内容,
'a'(附加), 'r+'(读取和写入)
"""
with open(filename, 'a') as file_object:
# 运用方法write将字符串导入文件
file_object.write('i love programming')
# 用try-except代码块处理异常,可避免出现traceback(错误消息与追溯)
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero")
# 通过try-except后的代码可通过else执行,即try-except-else代码块
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first = input('\nFirst number is: ')
if first == 'q':
break
second = input('Second number is: ')
if second == 'q':
break
try:
answer = int(first) / int(second)
# 进行到except时程序不会终止
except ZeroDivisionError:
print("You can't divide zero.")
else:
print(answer)
"""处理单个文件FileNotFoundError(文件不存在)异常"""
filename = 'alice.txt'
# 异常起始点在open,因此try在open之前
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " doesn't exist."
print(msg)
else:
# 用split分割字符串,并存储到列表中
words = contents.split()
num_word = len(words)
print(num_word)
def count_num(filename):
"""计算一个文件中包含多少单词"""
try:
with open(filename) as file_object:
contents = file_object.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " doesn't exist."
print(msg)
else:
# 用split分割字符串,并存储到列表中
words = contents.split()
num_word = len(words)
print(num_word)
# 简单使用pass,出措时不做提示
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_num(filename)
def count_num(filename):
"""计算一个文件中包含多少单词"""
try:
--snip--
except FileNotFoundError:
# 运用pass可以在程序出错时 ‘一声不吭’
pass
else:
--snip--
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_num(filename)
Python文件与异常 学习笔记
最新推荐文章于 2022-10-24 03:45:39 发布