文件和异常
在这里插入图片描述
一:读取文件
1.读取文件的全部内容
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text()
print(contents)
3.1415926535
8979323846
2643383279
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text()
contents=contents.rstrip() #rstrip() 能删除字符串末尾的空白
print(contents)
3.1415926535
8979323846
2643383279
## 读取文件内容时删除末尾的换行符
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text().rstrip()
contents=contents.rstrip()
print(contents)
3.1415926535
8979323846
2643383279
2.相对文件路径和绝对文件路径
3.访问文件中的各行—splitlines() 方法
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text()
lines=contents.splitlines()
for line in lines:
print(line)
3.1415926535
8979323846
2643383279
4.使用文件的内容
from pathlib import Path
path=Path('pi_digits.txt')
contents=path.read_text()
lines=contents.splitlines()
## 创建一个字符串
pi_string = ''
for line in lines:
pi_string += line
print(pi_string)
print(len(pi_string))
3.1415926535 8979323846 2643383279
36
5.包含 100 万位的大型文件
6.圆周率值中包含你的生日吗
birthday = input("Enter your birthday, in the form mmddyy: ")
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.")
Enter your birthday, in the form mmddyy: 0101
Your birthday does not appear in the first million digits of pi.
二:写入文件
1.写入一行 – write_text()
from pathlib import Path
path = Path('programming.txt')
path.write_text("I love programming.")
19
2.写入多行
from pathlib import Path
contents = "I love programming.\n"
contents += "I love creating new games.\n"
contents += "I also love working with data.\n"
path = Path('programming.txt')
path.write_text(contents)
## 会覆盖上次写的内容
78
三:异常-- try-except 代码块
1.处理 ZeroDivisionError 异常
2.使用 try-except 代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
You can't divide by zero!
3.使用异常避免崩溃 && else 代码块
4.处理 FileNotFoundError 异常 – 文件没找着
5.分析文本
6.使用多个文件
7.静默失败
四:存储数据
当用户关闭程序时,几乎总是要保存他们提供的信息。
一种简单的方式是使用模块 json 来存储数据。
模块 json 让你能够将简单的 Python 数据结构转换为 JSON 格式的字符串
1.使用 json.dumps() 和 json.loads()
json.dumps() 来存储(写入)这组数
json.loads() 来读取它们
json.dumps() 函数接受一个实参,即要转换为 JSON 格式的数据
from pathlib import Path
import json
numbers = [2, 3, 5, 7, 11, 13]
path = Path('numbers.json')
## json.dumps() 来存储
contents = json.dumps(numbers)
path.write_text(contents)
20
from pathlib import Path
import json
path = Path('numbers.json')
contents = path.read_text()
## json.loads() 来读取
numbers = json.loads(contents)
print(numbers)
[2, 3, 5, 7, 11, 13]
2.保存和读取用户生成的数据
例子:提示用户在首次运行程序时输入自己的名字,并且在他再次运行程序时仍然记得他。
传统方法:
改进方法:
3.重构
传统方法:
改进方法: