python从txt文件中读取数据返回字典
时间: 2023-12-29 20:07:39 浏览: 25
假设txt文件中的数据格式为每一行为一个键值对,键和值之间用等号连接,可以使用以下代码来读取数据并返回字典:
```python
def read_txt(file_path):
with open(file_path, 'r') as f:
lines = f.readlines()
data = {}
for line in lines:
line = line.strip() # 去除换行符和空格
if not line: # 跳过空行
continue
key, value = line.split('=') # 按照等号分割键值对
data[key] = value
return data
```
使用方法:
```python
data = read_txt('data.txt')
print(data)
```
其中,'data.txt'为待读取的txt文件路径。
相关问题
python从txt文件中读取保存的字典
可以使用以下代码从txt文件中读取保存的字典(假设字典以json格式保存):
```python
import json
with open('dictionary.txt', 'r') as f:
dictionary = json.load(f)
print(dictionary)
```
其中,`dictionary.txt`是保存字典的文件名。`json.load()`函数将读取文件并将其解析为字典对象。最后,我们将字典打印出来以确认读取是否成功。
python将字典写入文件以及从文件中读取字典数据
以下是Python将字典写入文件以及从文件中读取字典数据的示例:
1. 将字典写入文件:
```python
import json
data = {"name": "John", "age": 30, "city": "New York"}
with open("data.json", "w") as file:
json.dump(data, file)
```
2. 从文件中读取字典数据:
```python
import json
with open("data.json", "r") as file:
data = json.load(file)
print(data)
```