I am trying to convert csv into json file using python3. I keep getting this error, FileNotFound, when the csv file exists in the directory. Please help me fix the issue. Below is the code i tried. Also i would be grateful, if anyone could suggest how to transfer MongoDB database into a json file using python3.
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
Writing the files out using this code...
with open(outputfile, "a") as jsonfile:
jsonfile.write(json.dumps(data, indent=4))
Produces the following:
['adult_diapers.csv', 'groceries.csv', 'health_supplements.csv', 'mobility_aids.csv']
Here's my error in more detail:
---------------------------------------------------------------------------
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'
dir_path