文件和异常
- 文件就是和本地的一些格式的文件进行交互,比如我们经常看到的自动化办公,其实就是与本地的 Excel 文件交互;
- 异常是 python 中的一个特殊的对象,用于管理程序运行时出现的错误;
1.从文件中读取数据
读取整个文件
我们在目录下面新建一个 demo.txt
的文件,在其中写入:
然后我们编写 python 代码,来读取这一个文件:
with open('demo.txt', encoding='utf8') as file_object:
contents = file_object.read()
print(contents)
注意,如果我们这里的 open 没有第二个 encoding 参数,那么 python 会使用 gbk 的格式来解析文档,这时候可能会报错,但也不一定,因为还是需要根据你的 demo.txt
文档的格式来判断,比如我们这里:
很明显是 utf8 格式的,所以默认的 gbk 格式来解析这个文件就会报错,所以需要指定第二个参数为对应的格式即可。
如何关闭文件呢?
使用 close 关键字即可。
with open('demo.txt', encoding='utf8') as file_object:
contents = file_object.read()
print(contents)
# 关闭文件
file_object.close()
文件路径
在 windows 系统中,默认使用的文件路径是反斜杠\
,但是在代码中,我们依然可以直接使用/
来代替反斜杠使用。
逐行读取
我们上面是是直接使用 read 读取了整个文件,其实也可以选择逐行读取文件:
我们看到这里读取文件时,打印的时候加上了一个 rstrip() ,你可以把它去掉,看看它的作用是什么。
2.写入文件
我们再来看写入文件:
with open('demo.txt', 'w', encoding='utf8') as file_object:
file_object.write('Hello world')
with open('demo.txt', 'r', encoding='utf8') as file_object:
content = file_object.read()
print(content)
这里要注意的是,写入和读取需要再不同的两步进行。
3.异常
在 python 中,我们可以使用 try catch
来处理异常,用来防止程序崩溃。
try:
print(5/0)
except:
print("tmd, 0不能做除数!")
结果:
4.存储数据
熟悉前后端开发的同学肯定知道,一般我们传输数据都是使用的 JSON 格式。
在 python 中,我们可以使用 json.dump()
和 json.load()
来生成和读取 JSON 文件。
dump
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
这个时候观察目录,目录中多了一个文件,其中写入了我们的数组。
load
读取 JSON 文件:
import json
with open('numbers.json', 'r') as f_obj:
numbers = json.load(f_obj)
print(numbers)
结果: