文件读取
- 打开文件:当文件和.py不在同一目录下时,需要指定文件路径
with open('文件名') as 新的名字:
- 读取文件:read()——读取全文、readline()——读取第一行、readlines()——按行读取全文
(读取文本文件时,Python将所有的文本都解读为字符串,若读取的是数字,并想将其作为数字使用,则需要使用函数int()或者float()等)
写入文件
- 写入空文件——write()方法
with open (‘文件名’,‘w’) as 新名字:
- 在文件中添加——write()方法
with open (‘文件名’,‘a’)as 新名字
存储数据
使用模块json来存储
- json.dump()——将数据写入json文件
- json.load()——从json文件中读取数据
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
# 将数据写入json文件
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
# 从文件中将数据读取出来
with open(filename) as f_obj:
numbers_load = json.load(f_obj)
print(numbers_load)