【发布时间】:2020-11-20 16:17:55
【问题描述】:
我正在尝试遍历文件夹和子文件夹以访问和读取 CSV 文件,然后再将它们转换为 JSON。这是我正在处理的代码:
cursor = conn.cursor()
try:
# Specify the folder containing needed files
folderPath = 'C:\\Users\\myUser\\Desktop\\toUpload' # Or using input()
fwdPath = 'C:/Users/myUser/Desktop/toUpload'
for countries in os.listdir(folderPath):
for sectors in os.listdir(folderPath+'\\'+countries):
for file in os.listdir(folderPath+'\\'+countries+'\\'+sectors):
data = pd.DataFrame()
filename, _ext = os.path.splitext(os.path.basename(folderPath+'\\'+countries+'\\'+file))
print(file + ' ' + filename+ ' ' + sectors + ' ' + countries)
data = pd.read_csv(file)
# cursor.execute('SELECT * FROM SECTORS')
# print(list(cursor))
finally:
cursor.close()
conn.close()
下面的打印行将返回文件,其文件名不带扩展名,然后是扇区和国家文件夹名称:
print(file + ' ' + filename+ ' ' + sectors + ' ' + countries)
myfile.csv myfile WASHSector CTRYIrq
现在读取 CSV 会花费很多时间,最后 O 会收到以下错误:
[Errno 2] 文件 myfile.csv 不存在
【问题讨论】: