所以我知道这个问题可能会重复,但我只是想知道并理解如何从 TSV 文件转换为 JSON?我尝试到处搜索,但找不到线索或理解代码。
所以这不是 Python 代码,而是我想要转换为 JSON 的 TSV 文件:
title content difficulty
week01 python syntax very easy
week02 python data manipulation easy
week03 python files and requests intermediate
week04 python class and advanced concepts hard
这是我想要作为输出的 JSON 文件。
[{
"title": "week 01",
"content": "python syntax",
"difficulty": "very easy"
},
{
"title": "week 02",
"content": "python data manipulation",
"difficulty": "easy"
},
{
"title": "week 03",
"content": "python files and requests",
"difficulty": "intermediate"
},
{
"title": "week 04",
"content": "python class and advanced concepts",
"difficulty": "hard"
}
]
最佳答案
要使用 CSV 模块读取制表符分隔的数据,请使用 delimiter="\t"
参数:
更方便的是,CSV 模块有一个 DictReader,它会自动读取第一行作为列键,并将其余行作为字典返回:
with open('file.txt') as file:
reader = csv.DictReader(file, delimiter="\t")
data = list(reader)
return json.dumps(data)
JSON 模块还可以直接写入文件而不是字符串。
关于python - 如何从 TSV 文件转换为 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56439998/