Python txt文件读取写入字典的方法(json、eval)

一、使用json转换方法
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中,有多种方法可以从文件读取字典数据。以下是几种常见的实现方式: #### 方法一:使用`json`模块 如果字典是以JSON格式存储在文件中的,则可以利用`json.load()`函数来加载该字典。 ```python import json with open('data.json', 'r') as f: data_dict = json.load(f) print(data_dict) ``` 这种方法适用于当字典被序列化为JSON字符串并保存到文件的情况[^1]。 #### 方法二:使用`ast.literal_eval()` 对于一些简单的字典表示法(例如纯文本形式),可以直接通过`ast.literal_eval()`将其转换成字典对象。 ```python from ast import literal_eval with open('data.txt', 'r') as f: content = f.read() data_dict = literal_eval(content) print(data_dict) ``` 此方法适合处理那些未经过复杂编码的原始字典结构的数据文件[^2]。 #### 方法三:使用`pickle`模块 当需要更高效地保存和恢复复杂的Python对象时,可考虑采用`pickle`库来进行操作。 ```python import pickle with open('data.pkl', 'rb') as f: data_dict = pickle.load(f) print(data_dict) ``` 注意这打开模式设置为了'rb'(只读二进制),因为Pickle通常会以二进制的形式写入数据。 #### 方法四:使用`configparser`解析配置文件 假如目标字典来源于某种特定类型的配置文件(比如INI),那么借助于标准库的ConfigParser类也是一个不错的选择. ```python import configparser config = configparser.ConfigParser() config.read('settings.ini') section_name = list(config.keys())[1] data_dict = {key: value for key, value in config.items(section_name)} print(data_dict) ``` 上述例子展示了如何把一个ini风格的配置文档转化为普通的Python字典[^3]. 以上便是四种主要的方式用于解决“如何用Python文件读取字典数据”的问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值