文件和异常
从文件中读取数据
读取整个文件
with open('pi_digits.txt') as file_object:
contents=file_object.read()
print(contents.rstrip())
备注:函数open()返回一个表示文件的对象,此处将该对象赋给file_object;关键词with在不再需要访问文件后将其关闭;使用方法read()读取这个文件的全部内容;使用rstrip()删除字符串末尾的空白
文件路径
相对文件路径
代码中可以使用斜杠/
with open('text_files/filename.txt') as file_object:
绝对文件路径
如果一定使用反斜杠\,可对路径中的每个反斜杠都进行转义,如:
C:\\path\\to\\file.txt
file_path='/home/ehmattes/other_files/text_files/filename.txt'
with open (file_path) as file_object:
逐行读取
filename='pi_digits.txt'
with open (filename) as file_object:
for line in file_object:
print(line.rstrip())
创建一个包含文件各行内容的列表
filename='pi_digits.txt'
with open (filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
备注:方法readlines()从文件中读取每一行,并将其存储在一个列表中
使用文件的内容
filename='pi_digits.txt'
with open (filename) as file_object:
lines=file_object.readlines()
pi_string=''
for line in lines:
pi_string +=line.strip()
print(f'{pi_string[:52]}...')
print(len(pi_string))
备注:使用strip()删除原来位于每行左边的空格
写入文件
保存数据最简单的方式之一是将其写入文件中
写入空文件
将文本写入文件,在调用open()时需要提供另一个实参
python打开文件的模式包括
- 读取模式(‘r’)
- 写入模式(‘w’),在此模式打开下,如果要写入的文件不存在,函数open()将自动创建它,但若文件存在,python将在返回文件对象前清空该文件的内容
- 附加模式(‘a’),在此模式打开下,python不会在返回文件对象前清空文件的内容,而是将写入文件的行添加到文件末尾
- 读写模式(‘r+’)
python只能将字符串写入文本文件,要将数值数据存储到文本文件中,必须先使用**函数str()**将其转换为字符串格式
filename='programming.txt'
with open (filename,'w') as file_object:
file_object.write('I love programming.')
写入多行
如果需要每个字符串都单独占一行,需要在方法调用write()中包含换行符
filename='programming.txt'
with open (filename,'w') as file_object:
file_object.write('I love programming.\n')
file_object.write('I love creating new games.\n')
附加到文件
filename='programming.txt'
with open (filename,'a') as file_object:
file_object.write('I also love finding meaning in large datasets.\n')
file_object.write('I love creating apps that can run in a browser.\n')
异常
python使用称为异常的特殊对象来管理程序执行期间发生的错误,异常使用try-except代码块处理,代码运行时,即便出现异常,程序也将继续运行,显示编写的错误消息,如:
try:
print(5/0)
except ZeroDivisionError:
print('You can not divide by zero.')
else代码块
只有可能引发异常的代码才需要放在try语句中,有一些仅在try代码成功执行时才需要运行的代码,这些代码应放在else语句中,如:
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number=input("\nFist 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 not divide by zero.")
else:
print(answer)
分析文本
分析文本共包含的字数
**方法split()**以空格为分隔符将字符串分拆多个部分,并将这些不放呢都储存待一个列表中,如
titile='Alice in Wonderland'
title.spilt()
filename='alice.txt'
try:
with open(filename,encoding='utf-8') as f:
contents=f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
#计算该文件大致包含多少个单词
words=contents.split()
num_words=len(words)
print(f"The file {filename} has about {num_words} words.")
若分析多个文本,可以采用函数方式,如:
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename,encoding='utf-8') as f:
contents=f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
words=contents.split()
num_words=len(words)
print(f"The file {filename} has about {num_words} words.")
filenames=['alice.txt','siddhartha.txt','moby_dick.txt','little_women.txt']
for filename in filenames:
count_words(filename)
静默失败
pass语句,用于让Python在代码块中什么都不要做
def count_words(filename):
try:
with open (filename,encoding='utf-8') as f:
contents=f.read
except FileNotFoundError:
pass
else:
words=contents.split()
num_words=lens(words)
储存数据
使用json.dump()储存,使用json.load()读取
import json
numbers=[2,3,5,7,11,13]
filename='numbers.json'
with open (filename,'w') as f:
json.dump(numbers,f)
import json
filename='numbers.json'
with open(filename) as f:
numbers=json.load(f)
print(numbers)
import json
filename='username.json'
try:
with open(filename) as f:
username=json.load(f)
except FileNotFoundError:
username=input("What is your name?")
with open (filename,'w') as f:
json.dump(username,f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
重构
将代码划分为一系列完成具体工作的函数的过程称为重构,如
import json
def greet_user():
"""问候用户,并指出名字"""
filename='username.json'
try:
with open(filename) as f:
username=json.load(f)
except FileNotFoundError:
username=input("What is your name?")
with open (filename,'w') as f:
json.dump(username,f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
greet_user()
重构后变为:
import json
def get_stored_username():
"""如果储存了用户名,就获取它"""
filename='username.json'
try:
with open(filename) as f:
username=json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名"""
username=input("What is your name?")
filename='username.json'
with open (filename,'w') as f:
json.dump(username,f)
return username
def greet_user():
"""问候用户,并指出名字"""
username=get_stored_username()
if username:
print(f"Welcome back, {username}!")
else:
username=get_new_username():
print(f"We'll remember you when you come back, {username}!")