基本写法
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(type(data)) # 一般是 dict 或 list
print(data)
2026/1/25小于 1 分钟
import json
with open("data.json", "r", encoding="utf-8") as f:
data = json.load(f)
print(type(data)) # 一般是 dict 或 list
print(data)
import json
def read_jsonl(path):
data = []
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
data.append(json.loads(line))
return data
# 用法
records = read_jsonl("data.jsonl")
print(len(records))
print(records[0])
csv 模块import csv
rows = [
["id", "name", "score"],
[1, "Alice", 95],
[2, "Bob", 88],
[3, "Charlie", 92],
]
with open("output.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(rows)
print("CSV 写入完成")
import json
data = {
"name": "Alice",
"age": 25,
"skills": ["Python", "AI", "RAG"],
"active": True
}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
import networkx as nx
# 无向图
G = nx.Graph()
# 有向图
DG = nx.DiGraph()
# 多重图
MG = nx.MultiGraph()
# 多重有向图
MDG = nx.MultiDiGraph()
以graphml文件加载到networkx为例,文件基本信息:
<key id="d5" for="edge" attr.name="keywords" attr.type="string"/>
<key id="d4" for="edge" attr.name="description" attr.type="string"/>
<key id="d3" for="edge" attr.name="weight" attr.type="double"/>
<key id="d2" for="node" attr.name="source_id" attr.type="string"/>
<key id="d1" for="node" attr.name="description" attr.type="string"/>
<key id="d0" for="node" attr.name="entity_type" attr.type="string"/>
<graph edgedefault="directed">