![](/img/trans.png)
[英]Python: How do I write a list to file and then pull it back into memory (dict represented as a string convert to dict) later?
[英]How do I convert this string into a dict in python?
我有一个从mongodb导出到csv的字符串:这是一个示例:
[{"group":"Most Common","id":"00000000000002","name":"HVAC Specialists","name_singular":"HVAC Specialist"},{"group":"Other","id":"00000000001","name":"Hauling \u0026 Junk Removers","name_singular":"Hauling \u0026 Junk Remover"}]
我正在尝试将日期放入字典中,这样我就可以取出需要的内容并将其导出。
我尝试放入一个列表中,但是它从每个字母中创建了元素。
该字符串在txt文件中,我这样称呼它:
python stringwork.py thestring.txt
我看到了这个问题并尝试了以下操作:
from sys import argv
import json
# filename = argv
txt = open(argv[1])
json.loads(str(txt))
我得到了以下错误。
ValueError: No JSON object could be decoded
txt
变量是一个文件对象,不能转换为字符串。 因此,您应该阅读文件对象的内容,例如txt = open(argv[1]).readlines()
。 然后,您可以使用txt[0]
在txt
列表中获取字符串。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import argv
import json
filename = argv
txt = open(argv[1]).readlines()
a = json.loads(str(txt[0]))
print(a)
您在这里有点困惑:
txt = open(argv[1])
json.loads(str(txt))
在此之后, txt
是文件对象,而不是实际的字符串。
为此,您需要执行以下操作:
txt = open(argv[1]).read()
json.loads(txt)
这里txt
已经是包含文件内容的字符串,因此不需要str
。
请检查文件的读/写文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.