【问题标题】:How to convert bulk of csv into json如何将大量csv转换为json
【发布时间】:2020-08-01 09:02:48
【问题描述】:

以下是将一个csv文件转换为json的代码

列出目录中的所有文件

[data1.csv,data2.csv,data.csv]

以下是将一个文件转换为 json 的代码。就像我需要循环所有文件

import csv 
import json 
import os
import glob

os.chdir(r'dir' )
result = glob.glob( '*.csv' )
print (result) 
def make_json(csvFilePath, jsonFilePath): 
      
    for i in result:
        data = {} 
        with open(csvFilePath, encoding='utf-8') as csvf: 
            csvReader = csv.DictReader(csvf) 
            for rows in csvReader: 
                key = rows['id'] 
                data[key] = rows 
        with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: 
            jsonf.write(json.dumps(data, indent=4)) 
        csvFilePath =f"{i}"
        jsonFilePath =f"{i.split('.')[-2]}.json"
make_json(csvFilePath, jsonFilePath)

我有类似的文件需要转换成 json。在每个文件中id 是主键

那里有很多文件。我不想每次都更改 csvFilePath 和 jsonFilePath。

面临的问题?

  • 我所有的json文件都以.csv.json结尾
  • 最后一个文件名 data9.csv 未转换为 json 并且 data2 转换为 data2.json 和 data2.csv.json 的两倍

【问题讨论】:

  • @WeavingBird1917 有很多文件。我不想每次都更改 csvFilePath 和 jsonFilePath
  • @WeavingBird1917,这不是一个错字,而是一个变量名。
  • 要遍历目录中的文件,您可以使用os.listdir()(仅限当前目录)或os.walk()(递归目录)。
  • 你能澄清你的问题吗?如果您可以转换一个文件,那么是什么阻止您转换一个又一个文件?您显然已经知道如何使用 for 循环,您有什么麻烦循环文件名以在每个文件上调用 make_json
  • 看看str.replace()函数,你可以用.json替换名字的.csv部分。

标签: python json csv


【解决方案1】:

这是一种方法,

import glob
import pandas as pd

for csv_f in glob.glob('/<file_path>/*.csv'):
    with open(f'{csv_f.replace(".csv", ".json")}', "w") as f:
        pd.read_csv(csv_f).set_index('id') \
            .to_json(f, orient='index')

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多