简体   繁体   中英

FileNotFoundError: [Errno 2] No such file or directory: error

I'm looping through many folders to get any JSON file in each folder using the following code:

def get_all_jobs():
    for root_dir, _, file_names in os.walk(r'path'):
        for file_name in file_names:
            if file_name.endswith('.json'):
                all_files = (f'{root_dir}/{file_name}')
                for file in all_files:
                    with open(file_name, 'r', encoding="utf8") as json_file:
                        read_content = json.loads(json_file.read())

and I get this error :

FileNotFoundError: [Errno 2] No such file or directory:

and don't have one path to one folder to give but I have many folders in which I have the files. How can I solve this?

find the information about glob here . glob will escape all the inside directories and match our pattern recursively.

def get_all_jobs():    
    for json_file in glob.iglob(path+"/**/*.json".replace('/',os.path.sep),recursive=True):
        with open(json_file, 'r', encoding="utf8") as jf:
            read_content = json.loads(jf.read())

Note: here path is the base directory where you have multiple folders which has your json files.

Explanation :

Here glob goes to your base directory path , from there recursively it goes to all sub folders and checks if any file contains .json extension, If it has, then it gives complete path of that file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM