繁体   English   中英

如何从 TSV 文件转换为 JSON 文件?

[英]How to convert from TSV file to JSON file?

所以我知道这个问题可能会重复,但我只是想知道并了解如何从 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"
    }
]

您需要的内置模块是csvjson

要使用 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 模块也可以直接写入文件而不是字符串。

如果您使用的是pandas您可以使用带有选项orient="records"to_json方法来获取您想要的条目列表。

my_data_frame.to_json(orient="records")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM