python - 要列出的文件内容,但不是字符串
问题描述
我正在尝试将带有字典的嵌套列表从 txt 文件附加到新列表中。我所做的一切,内容总是成为新列表中的字符串。
是否可以按原样从文件中读取数据并将其附加到列表中,就像嵌套列表一样?
这是我的代码:
dataFile = "library.txt"
with open(dataFile) as myfile:
data="".join(line.rstrip() for line in myfile)
data2=data.replace(" ","")
newLibraryList = []
newLibraryList.append(data2)
print(newLibraryList)
library.txt 内容如下所示。
[
{"name": "brick"},
{"dim": "0.108"},
{"lamdbaValue": "0.610"},
{"zValue": "5.000"},
{"fireValue": "A"}
],
[
{"name": "brick"},
{"dim": "0.108"},
{"lamdbaValue": "0.800"},
{"zValue": "5.400"},
{"fireValue": "A"}
]
如果有人可以帮助我或指出我正确的方向,我真的很感激。
提前谢谢
解决方案
您的文件的某些部分类似于 JSON - 问题是:总共是无效的JSON。
这个:
[
{"name": "brick"},
{"dim": "0.108"},
{"lamdbaValue": "0.610"},
{"zValue": "5.000"},
{"fireValue": "A"}
]
对于包含 5 个字典(每个字典有 1 个键/值)的 1 元素列表是有效的 JSON。
下面的代码使用字符串拆分和魔法从您发布的演示数据中创建“有效”部分,然后使用JSON.loads(string)从中创建 python 对象。它很脆弱 - 如果您的文件中有任何错误,它将输出错误并跳过它。
它取决于拆分],
- 如果您曾经在数据部分中添加这些拆分,它将破坏并且您必须修复它。
创建演示文件(一个数据集已损坏 - 丢失 } 等):
fn = "library.txt"
with open(fn,"w") as f:
f.write("""[
{"name": "brick"},
{"dim": "0.108"},
{"lamdbaValue": "0.610"},
{"zValue": "5.000"},
{"fireValue": "A"}
],
[
{"name": "brick",
{"dim": "0.108"},
{"lamdbaValue": "0.800"},
{"zValue": "5.400",
{"fireValue": "A"}
],
[
{"name": "brick"},
{"dim": "0.108"},
{"lamdbaValue": "0.800"},
{"zValue": "5.400"},
{"fireValue": "A"}
]""")
解析:
import json
lib = []
with open(fn,"r") as r:
text = r.read()
spl = [t.rstrip("]").replace(" ","").replace("\n"," ")+"]" for t in text.split("],")]
parts = []
for p in spl:
try:
parts.append(json.loads(p))
except json.JSONDecodeError as e:
print("Skipping: ", p)
print(e)
# parts = [json.loads(p) for p in spl] # removed list comp for better
# exception text output/messages
lib.extend(parts)
for l in lib:
print(l)
输出:
Skipping: [ {"name":"brick", {"dim":"0.108"}, {"lamdbaValue":"0.800"}, {"zValue":"5.400", {"fireValue":"A"} ]
Expecting property name enclosed in double quotes: line 1 column 21 (char 20)
[{'name': 'brick'}, {'dim': '0.108'}, {'lamdbaValue': '0.610'},
{'zValue': '5.000'}, {'fireValue': 'A'}]
[{'name': 'brick'}, {'dim': '0.108'}, {'lamdbaValue': '0.800'},
{'zValue': '5.400'}, {'fireValue': 'A'}]
将您的数据转换为有效的 json可能是值得的,这将大大简化:
fn = "library.txt" # contains a list of dictionarys, each dict is one item
with open(fn,"w") as f:
f.write("""[
{"name": "brick",
"dim": "0.108",
"lamdbaValue": "0.610",
"zValue": "5.000",
"fireValue": "A"}
,
{"name": "brick",
"dim": "0.108",
"lamdbaValue": "0.800",
"zValue": "5.400",
"fireValue": "A"}
,
{"name": "brick",
"dim": "0.108",
"lamdbaValue": "0.800",
"zValue": "5.400",
"fireValue": "A"}
]""")
import json
lib = []
with open(fn,"r") as r:
loaded_libs = json.load(r)
lib.extend(loaded_libs)
for l in lib:
print(l)
输出:
{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.610',
'zValue': '5.000', 'fireValue': 'A'}
{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.800',
'zValue': '5.400', 'fireValue': 'A'}
{'name': 'brick', 'dim': '0.108', 'lamdbaValue': '0.800',
'zValue': '5.400', 'fireValue': 'A'}
推荐阅读
- netsuite - NetSuite rest api 问题说错误 500 - 找不到页面
- r - R Shiny App 的字体没有出现在 bslib 中
- python - FiPy 中的变量约束
- html - 如何在css中悬停时更改光标类型
- javascript - 映射对象并返回具有现有值的数组更改了新值
- javascript - React 初始呈现 null 值,但稍后更新。需要将值设置为初始状态
- javascript - 使用 Ramda 基于多个条件过滤列表
- python - 使用 Django(第一个应用程序)找不到页面(404)
- azure - Azure 服务总线高可用性和跨区域复制
- python - 使用 pyautogui 定位相似图像的第二个位置