【问题标题】:Dynamic folder paths for JSON file from CSVs?来自 CSV 的 JSON 文件的动态文件夹路径?
【发布时间】:2021-02-17 18:37:25
【问题描述】:

我有以下用于创建 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()

【问题讨论】:

  • 为什么csv2jsonindirectory 是一个类?它只有一个方法,而且该方法根本不使用实例 (self)。
  • 是的,有可能。你想把最后两个字符改成什么?该信息的来源是什么。您也可能不需要将反斜杠更改为正斜杠。
  • 我想更改(路径中的两位数字值最多 150.. 即 AA、AB、AC、AD.......这些是我的 CSV 所在的文件夹名称。 ....

标签: python json python-3.x csv


【解决方案1】:

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

【讨论】:

  • 我的文件夹在同一路径中更改(A1、A2、A3 等)。让我试试它是否有效....
  • “不工作”相当模糊。究竟是什么不起作用,错误消息是什么?您可以更新您的初始帖子以包含您的整个代码和错误。
【解决方案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)

【讨论】:

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