------ 文件和异常------
------从文件中读取数据------
先创建文件qingtian.txt
with open (‘qingtian.txt’,’+r’,encoding=‘UTF-8’) as f:
a=f.read()
print(a)
------- 文件的路径-------
—相对路径—
根据你组织文件的方式,有时可能要打开不在程序文件所属目录中的文件。例如,你可能将程序文件存储在了文件夹python_work中,而在文件夹python_work中,有一个名为
text_files的文件夹,用于存储程序文件操作的文本文件。虽然文件夹text_files包含在文件夹python_work中,但仅向open() 传递位于该文件夹中的文件的名称也不可行,因为Python 只在文件夹python_work中查找,而不会在其子文件夹text_files中查找。要让Python打开不与程序文件位于同一个目录中的文件,需要提供文件路径 ,它让Python到系统的特定位置
去查找。
由于文件夹text_files位于文件夹python_work中,因此可使用相对文件路 径来打开该文件夹中的文件。相对文件路径让Python到指定的位置去查找,而该位置是相对于当前运行的程
序所在目录的。在Linux和OS X中,你可以这样编写代码:
with open(‘text_files/filename.txt’) as file_object:
a=file_object.read()
print(a)
—绝对路径—
还可以将文件在计算机中的准确位置告诉Python,这样就不用关心当前运行的程序存储在什么地方了。这称为绝对文件路径 。
import os
file_path = ‘python_18/qingtian.txt’
with open(file_path) as file_object:
a = file_object.read()
print(a)
异常
Python使用被称为异常 的特殊对象来管理程序执行期间发生的错误。每当发生让Python不知所措的错误时,它都会创建一个异常对象。如果你编写了处理该异常的代码,程序将继
续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告。
异常是使用try-except 代码块处理的。try-except 代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。使用了try-except 代码块时,即便出现异常,
程序也将继续运行:显示你编写的友好的错误消息,而不是令用户迷惑的traceback
for example①
print(5/0)
运行后显示
Traceback (most recent call last):
File “C:/Users/xiaoliu/Documents/Tencent Files/3230614498/FileRecv/异常.py”, line 36, in
print(5/0)
ZeroDivisionError: division by zero
使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print(“You can’t divide by zero!”)
for example ②
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
answer = int(first_number) / int(second_number)
print(answer)
当输入first number为5 last number为0时异常
对上面的代码进行优化 添加异常
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: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print(“You can’t divide by 0!”)
else:
print(answer)
处理文件异常
filename = ‘alice.txt’
with open(filename) as f_obj:
contents = f_obj.read()
进行处理
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)
对文本分析(当文件存在时有字母时)
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)
else:
# 计算文件大致包含多少个单词
words = contents.split()
num_words = len(words)
print(“The file " + filename + " has about " + str(num_words) + " words.”)
失败时可以直接pass例如
def count_words(filename):
“”“计算一个文件大致包含多少个单词”""
try:
# 监控代码块
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass#失败直接pass处理
else:
words = contents.split()
num_words = len(words)
print(“The file " + filename + " has about " + str(num_words) + " words.”)
filenames = [‘alice.txt’, ‘siddhartha.txt’, ‘moby_dick.txt’, ‘little_women.txt’]
for filename in filenames:
count_words(filename)
-----异常里面的finally-----
finally是无论异常不异常都会运行的模块
try:
# 监控代码块
except +异常类型 as+别名异常
# 进行异常处理:
raise 别名异常(把异常抛出来可加也可以不加)
else:
运行程序(不异常时进行的代码块)
finally:
运行程序(无论异常异常不异常都运行的可以加也可以不加)