将.csv转换为.jsonl python

2024-10-02 22:37:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.csv文件,我想把它转换成.jsonl文件

我找到了Pandasto_json方法:

df = pd.read_csv('DIRECTORY/texts1.csv', sep=';')
df.to_json ('DIRECTORY/texts1.json')

但是,我不知道有什么函数可以将其转换为.jsonl格式。我该怎么做


Tags: 文件csvto方法函数jsondfread
1条回答
网友
1楼 · 发布于 2024-10-02 22:37:30

我不确定这个结果是否符合“jsonl”语法,但这是一个可能会导致相关结果的黑客行为

主要技巧是在导出时将输入文件的每一行视为单独的JSON文件,然后从磁盘读回JSON并将其视为不同的jsonl行

我从一个包含

hello, from, this, file
another, amazing, line, csv
last, line, of, file

下面的代码段基于another post

import pandas
df = pandas.read_csv("myfile.csv", header=None)

file_to_write = ""
for index in df.index:
    df.loc[index].to_json("row{}.json".format(index))
    with open("row{}.json".format(index)) as file_handle:
        file_content = file_handle.read()
        file_to_write += file_content + "\n"
        
with open("result.jsonl","w") as file_handle:
    file_handle.write(file_to_write)

生成的.jsonl文件包含

{"0":"hello","1":" from","2":" this","3":" file"}
{"0":"another","1":" amazing","2":" line","3":" csv"}
{"0":"last","1":" line","2":" of","3":" file"}

如果不需要行索引,可以从上面Python代码段的.to_json()行中删除这些索引

相关问题 更多 >