CSV中JSON文件的动态文件夹路径?

2024-09-21 03:27:37 发布

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

我使用以下python代码创建JSON文件。我需要为我的项目多次运行此代码,即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()

Tags: csvtopath代码inimportjsonwith
2条回答

做了一些研究,终于找到了答案

import csv
import json
import os
import time

class csv2jsonindirectory():
    
    def Python_trial(self):
        # Update the following variable with the path in windows and replace
        # every "\" with "/".
        
        path_to_folder = "CSV Folder Path"

        path = "Path to folder to save JSON files"

        for root , dirs, files in os.walk(path_to_folder):
            print(os.path.basename(root))
            csv_files = []
            mydict= {}
            for file in files:
                if file.endswith('.csv'):
                    file_path = root+'/'+file
                    csv_files.append(file_path)
            for i in range(len(csv_files)):
                with open(csv_files[i]) as f:
                     csvreader = csv.DictReader(f)
                     rows = list(csvreader)
                     mydict["chartdiv" + str(i + 1)] = rows
            with open(path+'/' +os.path.basename(root)+ ".json", 'w') as f:
                  json.dump(mydict, f, indent= 4)
            del csv_files
            del mydict
start = time.time()                  
dd = csv2jsonindirectory()
dd.Python_trial()
end=time.time()
print(end - start)

我不能完全肯定我对你的理解是否正确。如果要对不同的路径执行此TAK,可以通过向此类添加一个__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()

相关问题 更多 >

    热门问题