Python txt文件读取写入字典的方法(json、eval)
2017-10-11 14:39
1166 查看
一、使用json转换方法
1、字典写入txt
2、读取txt中的字典
二、使用str转换方法
1、字典写入txt
2、读取txt中字典
1、字典写入txt
import json dic = { 'andy':{ 'age': 23, 'city': 'beijing', 'skill': 'python' }, 'william': { 'age': 25, 'city': 'shanghai', 'skill': 'js' } } js = json.dumps(dic) file = open('test.txt', 'w') file.write(js) file.close()
2、读取txt中的字典
import json file = open('test.txt', 'r') js = file.read() dic = json.loads(js) print(dic) file.close()
二、使用str转换方法
1、字典写入txt
dic = { 'andy':{ 'age': 23, 'city': 'beijing', 'skill': 'python' }, 'william': { 'age': 25, 'city': 'shanghai', 'skill': 'js' } } fw = open("test.txt",'w+') fw.write(str(dic)) #把字典转化为str fw.close()
2、读取txt中字典
fr = open("test.txt",'r+') dic = eval(fr.read()) #读取的str转换为字典 print(dic) fr.close()
相关文章推荐
- python菜鸟笔记--python读取和写入txt文件的方法
- Python读取Json字典写入Excel表格的方法
- python 读写txt文件 json文件的实现方法
- 我用python将结果写入txt文件出现的编码问题及其解决方法
- nodejs 读取JSON文件写入txt中 fs.readFile&fs.writeFile
- python中对于json写入txt文件的编码问题
- C++中Txt文件读取和写入(方法汇总)
- Python之读取TXT文件的三种方法
- Python读取json文件,并转化为字典进行提取字段(出现索引must be int,not str)解决方案
- Spring Batch读取txt文件并写入数据库的方法教程
- Asp.net读取和写入txt文件方法(实例)!
- Python 读取写入 json 格式的文件
- php逐行读取txt文件写入数组的方法
- 用python读取、写入txt文件
- unity中从txt文件中读取解析json数据&&unity中json数据写入txt文件
- php逐行读取txt文件写入数组的方法
- python 字典中有中文,写入文件变为编码的解决方法
- python读取json文件并将数据插入到mongodb的方法
- python3将csv文件中的两列数据读取出来,并且按行写入txt文本之中
- 使用java 程序创建格式为utf-8文件的方法(写入和读取json文件)