Exporting multiple json files to specific folder python

Question:

My part of code is

    js_file = response.text
    filename = [x for x in df['col1']]
    for names in filename:
        with open(names, 'w') as outfile:
           json.dump(js_file,outfile)

What i need to do is to export to specific folder which doesn’t exist and specify the extension of filenames

for an example for the extension:

  • filename1.json
  • filename2.json
  • … so on

I know it’s already exported as json file but i need to know how to add the extension to multiple files and put files in specific folder that doesn’t exist

Your help will be appreciated.

Asked By: Peter

||

Answers:

The following code can be used

import pathlib
import os
js_file = response.text
# expecting json filenames present in col1 like " 'filename1', 'filename2' "
filenames = df['col1']
parent_folder = "folder_name"
pathlib.Path(parent_folder).mkdir(parents=True, exist_ok=True)
for names in filename:
  json_file_name = os.path.join(parent_folder, names+".json" )
  with open(json_file_name, 'w') as outfile:
     json.dump(js_file,outfile)
Answered By: Basir Mahmood
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.