Home > OS >  Loop through a directory and add filename to dictionary
Loop through a directory and add filename to dictionary

Time:02-28

I am rather new to Python and trying to learn this in my spare time. The goal of the task I am working on is to read a system directory and add the filename to a dictionary. I was able to just add it to a list, but I need to have a key that is an integer that I can use in a for loop. So after doing some reading, I think if I can loop through this directory and add an counter as the key and the filename as the value that would give me what I want. Here is what I have tried so far and if I am thinking about this the wrong way, please let me know. Also if I did not explain this clearly enough, I would be happy to try to provide more information. TYIA!

import os

def list_json_files():

    path_of_directory = 'C:\\JSON_Test\\json_files'
    list_of_files = {}
    ext = ('.json')

    for my_files in os.listdir(path_of_directory):
        if my_files.endswith(ext):
            # stuck and missing code 
        else:
            continue
    
    return list_of_files

list_json_files()

## added to code

def write_csv():
    list_of_files = list_json_files()
    for my_file in list_of_files:        
        row = create_list_from_json(f'json_files/{my_file}')  
        with open('output.csv', 'a') as c:
            writer = csv.writer(c)
            writer.writerow(row)

CodePudding user response:

You could try this, if your aim is to read list of files ending with .json and write it to a file.

Code changes from the original

  1. Using glob, code is simpler to fetch files ending with particular extension. Hence using glob instead of os.listdir
  2. Using normal file writer, instead of csv module, as I feel it would be sufficient for this scenario.

Code

import glob
import os.path

def list_json_files():
    path_of_directory = 'C:\\JSON_Test\\json_files'
    ext = ('*.json')
    list_of_files = glob.glob(os.path.join(path_of_directory, ext))
    return list_of_files

def write_csv():
    list_of_files = list_json_files()
    with open('output.csv', 'a') as myfile:
        myfile.write('\n'.join(list_of_files))

write_csv()
  • Related