首页 > 解决方案 > 来自 CSV 的 JSON 文件的动态文件夹路径?

问题描述

我有以下用于创建 JSON 文件的 python 代码。我需要为我的项目多次运行此代码——即 150 次。有什么办法可以让它动态吗?对于整个代码,只有最后两个字符在给定的:path_to_folder = "C:\\Users\\CSVs\\AO".

import csv
import json
import glob
import os

class csv2jsonindirectory():
    def Python_trial(self):
        # Update the following variable with the path in windows and replace
        # every "\" with "/".
        path_to_folder = "C:\\Users\\CSVs\\AO"
        csv_files_in_folder = path_to_folder + '/*.csv'
        csvfilenames = []
        i = 1
        mydict = {}
        for filename in glob.glob(csv_files_in_folder):
            csvfilenames.append(os.path.splitext(filename)[0])
            rows = []
        for i in range(len(csvfilenames)):
            with open(csvfilenames[i] + ".csv", "r") as f:
                csvreader = csv.DictReader(f)
                rows = list(csvreader)
                mydict["chartdiv" + str(i + 1)] = rows

        print(mydict)

        with open(csvfilenames[0] + ".json", 'w') as f:
            json.dump(mydict, f, indent= 4)


dd = csv2jsonindirectory()
dd.Python_trial()

标签: pythonjsonpython-3.xcsv

解决方案


我不完全确定我是否正确理解了您。如果您想为不同的路径执行此任务,您可以通过向__init__()此类添加一个将路径作为参数的方法来实现。然后你可以遍历目录:

class csv2jsonindirectory():
    def __init__(self,path):
        self.path = path
    def Python_trial(self):
        # Update the following variable with the path in windows and replace
        # every "\" with "/".
        csv_files_in_folder = self.path + '/*.csv'
        
   ### [Remainder of your code]



for folder in ["A0","A1","A3"]:
    path = "C:/Users/CSVs/"+folder
    dd = csv2jsonindirectory(path)
    dd.Python_trial()

推荐阅读