文件读取
读取整个文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
open() 打开读取文件
read()读入文件
with用于自动关闭文件流
文件路径
- 相对路径
相对路径在程序所在目录 - 绝对路径
物理路径
注意:文件路径使用反斜杠.而反斜杠为转义标记.为确保万无一失,使用原始字符串,即在开头的单引号前加上r
逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
读取文件内容存储在列表中
lines = file_object.readlines()
写入文件
写入空文件
with open(filename, 'w') as file_object
file_object.write("something")
open的第二个参数
- 写入模式 'w'
如果文件已经存在,则清空文件 - 读取模式'r'
- 附加模式 'a'
- 读取写入模式 'r+'
- 省略模式实参,默认为只读模式
- python中只能将字符串写入文件,数值型数据要存入文件之中要先使用str转为字符串
写入多行
文本末尾加入\n换行符
附加到文件
指定模式实参为 a 追加模式
异常
使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
else代码块
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
用于执行try代码块中代码成功执行后执行
存储数据
json
- json.dump() 输出json至文件
两个参数
- 要存储的数据
- 用来存储的文件对象
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
- json.load() 从文件中读取json
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)