0

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'
2
  • Is the full path specified? Looks like it's just the filename and not the full path to the file. Add dir_path Commented Jun 24, 2019 at 7:08
  • Thanks a lot. I need to coorect by mentioning os.join(dir_path) Commented Jun 24, 2019 at 7:18

1 Answer 1

1

Is the full path specified? Looks like it's just the filename and not the full path to the file. Add dir_path and use os.path.join() to concatenate the path and the filename as follows:

with open(os.path.join(dir_path, file), "r") as csvfile:
    reader = csv.DictReader(csvfile)

And your final code becomes:

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.