我正在尝试使用python3将csv转换为json文件。目录中存在csv文件时,我不断收到此错误FileNotFound。请帮助我解决问题。下面是我尝试的代码。如果有人可以建议如何使用python3将MongoDB数据库转换为json文件,我也将不胜感激。
import csv, json, os
#get all csv files from the directory
dir_path = r'C:\Users\USER\Desktop\output_files'
inputfile = [file for file in os.listdir(dir_path) if file.endswith('.csv')]
print(inputfile)
for file in inputfile:
with open(file, "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
id = row['ID']
data[id] = row
使用此代码写出文件...
with open(outputfile, "a") as jsonfile:
jsonfile.write(json.dumps(data, indent=4))
产生以下内容:
['adult_diapers.csv', 'groceries.csv', 'health_supplements.csv', 'mobility_aids.csv']
这是我的更详细的错误:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-17-1aac06308031> in <module>
6 print(inputfile)
7 for file in inputfile:
----> 8 with open(file, "r") as csvfile:
9 reader = csv.DictReader(csvfile)
10 for row in reader:
FileNotFoundError: [Errno 2] No such file or directory: 'adult_diapers.csv'
答案 0 :(得分:1)
是否指定了完整路径?看起来它只是文件名,而不是文件的完整路径。添加dir_path
并使用os.path.join()
连接路径和文件名,如下所示:
with open(os.path.join(dir_path, file), "r") as csvfile:
reader = csv.DictReader(csvfile)
您的最终代码变为:
import csv, json, os
#get all csv files from the directory
dir_path = r'C:\Users\USER\Desktop\output_files'
inputfile = [file for file in os.listdir(dir_path) if file.endswith('.csv')]
print(inputfile)
for file in inputfile:
with open(os.path.join(dir_path, file), "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
id = row['ID']
data[id] = row
with open(outputfile, "a") as jsonfile:
jsonfile.write(json.dumps(data, indent=4))