将 .csv 转换为 .jsonl python

问题描述 投票:0回答:3

我有一个 .csv 文件,我想将其转换为 .jsonl 文件。

我找到了Pandas

to_json
方法:

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

但是,我不知道有什么函数可以将其转换为 .jsonl 格式。我怎样才能做到这一点?

python json pandas csv data-conversion
3个回答
4
投票

这可能有点晚了,但我写了一个名为 csv-jsonl 的愚蠢模块,它可能有助于解决此类问题。

>>> from csv_jsonl import JSONLinesDictWriter
>>> l = [{"foo": "bar", "bat": 1}, {"foo": "bar", "bat": 2}]
>>> with open("foo.jsonl", "w", encoding="utf-8") as _fh:
...     writer = JSONLinesDictWriter(_fh)
...     writer.writerows(l)
...

它扩展了原生的

csv
模块,所以它是最熟悉的。希望有帮助。


2
投票

我不确定这个结果是否符合“jsonl”语法,但这是一个可能会得到相关结果的黑客攻击。

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

我从包含以下内容的 CSV 开始

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

下面的代码片段基于 另一篇文章

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() 行中删除这些索引。


0
投票

认为应该添加这一点。此版本基于 Ben 的答案,但避免使用临时文件并优化字符串处理,从而解决原始脚本中潜在的低效率和问题。

import pandas as pd

# Reading the CSV file into a DataFrame without headers
df = pd.read_csv("myfile.csv", header=None)

# Prepare an empty list to collect JSON strings
json_lines = []

# Convert each row to a JSON string and append it to the list
for index, row in df.iterrows():
    json_str = row.to_json(orient='records')
    json_lines.append(json_str)

# Join all JSON strings with newline characters and write to a single file
with open("result.jsonl", "w") as file_handle:
    file_handle.write("\n".join(json_lines))
© www.soinside.com 2019 - 2024. All rights reserved.