【发布时间】: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