本文介绍了尝试将较大的tsv文件转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tsv文件,我需要将其转换为json文件。我正在使用此python脚本导出一个空的json文件。

I've a tsv file, which I need to convert it into a json file. I'm using this python script which is exporting a empty json file.

import json
data={}
with open('data.json', 'w') as outfile,open("data.tsv","r") as f:
for line in f:
   sp=line.split()
   data.setdefault("data",[])
json.dump(data, outfile)


推荐答案

您永远不要在代码中使用 sp

You never use the sp in your code.

要正确转换tsv,您应该分别阅读第一行以获得列名,然后阅读以下各行并填充字典列表。

To properly convert the tsv, you should read the first line separately, to get the "column names", then read the following lines and populate a list of dictionaries.

这是您的代码应为的样子:

Here's what your code should look like:

import json
data=[{}]
with open('data.json', 'w') as outfile, open("data.tsv","r") as f:
firstline = f.readline()
columns = firstline.split()
lines = f.readlines()[1:]
for line in lines:
    values = line.split()
    entry = dict(zip(columns, values))
    data.append(entry)
json.dump(data, outfile)

此w会输出一个包含tsv行列表的文件作为对象。

This will output a file containing a list of tsv rows as objects.

这篇关于尝试将较大的tsv文件转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 22:01