[PYTHON] Scan all your local directory files

Scan local files in directory

At certain times, we may need to perform scanning for all the files stored in local directory. We can perform so using the code as follows:


import os
    # scan all files in directory
    for file in os.listdir('.'):
        if file.endswith('.json'):
             # perform action here
             print(file) # for testing purpose, we are merely print the file names

However, printing the file names may not be enough. Let’s try to perform some further actions: read and scan all the json files in the local directory, combine (remove duplicate) and print it out!


import os
import json

# defining the lists
all_json = []
    # scan all files in directory
    for file in os.listdir('.'):
        if file.endswith('.json'):
            # action starts here
            with open(os.path.abspath('') + '/' + file) as f:
                # to union: convert the list into set
                # and uses "|" to UNION it
                all_json = list(set(all_json) | set(json.load(f)))
                # Sort the lit
                all_json.sort()

# print the combined jsons
print(all_json)