- 文件读取
- 文件路径
- 整体读取
- 逐行读取
- 数据存储进列表
- 写入文件
- 写入新文件
- 已有文件添加内容
- json存储数据
- dump()存储
- load()读取
- 绝对路径
- 相对路径:相对当前文件夹下的路径
Linux与OS X采用/
dir = 'text_files/filename.txt'
Windows采用
dir = 'text_filesfilename.txt'整体读取
#关键字with在不再需要访问文件后将其关闭
with open(dir) as file: #打开文件
content = file.read()
print(content)
采用read()读取后是末尾相对原文多了一个空行,因为read()到达文件末尾时返回一个空字符串
可以采用:
print(content.rstrip())逐行读取
with open(dir) as file:
for line in file:
print(line)
如果读取文件中每行都有一个/n换行符,读取时/n也会读取,会出现每次读取多一个空行,可以采用rstrip()消除
数据存储进列表with open(dir) as file: lines = file.readlines()写入文件 写入新文件
open()中:
- 'r'为读
- 'w'为写
- 'a'为附加
with open(dir, 'w') as file:
file.write('内容')
已有文件添加内容
不覆盖原有文件,而在文件后添加内容
with open(dir ,'a') as file:
file.write('内容')
json存储数据
import json list = [1, 2, 3, 4]dump()存储
函数json.dump()接受两个实参:
- 要存储的数据
- 可用于存储数据的文件对象。
with open(dir, 'w') as file:
json.dump(list, file)
load()读取
with open(dir) as file:
num = json.load(file)



