python - 来自 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()
解决方案
我不完全确定我是否正确理解了您。如果您想为不同的路径执行此任务,您可以通过向__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()
推荐阅读
- css - 在滑块底部定位图像
- gdb - 如何将 pwndbg 上下文中的语法设置为 AT&T?
- python-3.x - 将嵌套的 IF 条件转换为 Python 中的嵌套列表
- flutter - 如何解决列表视图中的索引不正确
- javascript - 新智能按钮 API 中的 no_shipping 选项
- php - 我试图下载图像,但我只得到一张图像
- r - 抵消 GLM 因子 R - 标准误差
- html - 如何防止 div 在小屏幕 Bootstrap 中进入另一个 div
- sql - postgresql,根据条件获取数据
- javascript - 在 AWS Lambda 中使用 JSON 对象请求数据时出现 CORS 错误