Home > Back-end >  FileNotFoundError raceback (most recent call last) while using os.listdir()
FileNotFoundError raceback (most recent call last) while using os.listdir()

Time:07-07

I am facing a problem of file not found. os.listdir() method should be able to load folder. Why it cannot work correctly? Make me any advice and suggestions. Thank you.

scene = 'scene1'
folders = os.listdir("graph_state_list/"   scene   "/")
for folder in folders:
    try:
        activity_directory = "graph_state_list/"   scene   "/"   folder
        directories = os.listdir(activity_directory)
        program_discription_list = []
        for directory in directories:    
            program_description_path = "graph_state_list/"   scene   "/"   folder   "/"   directory   "/program-description.txt"
            program_description = {}
            input_file = open(program_description_path, "r")
            name_desc = []
            for line in input_file:
                name_desc.append(line.strip())
            input_file.close()
            program_description = {
                "name": name_desc[0],
                "description": name_desc[1]
            }
            program_discription_list.append(program_description)
            activity_program = get_activity_program("graph_state_list/"   scene   "/"   folder   "/"   directory   "/activityList-program.txt")
            graph_state_list = get_graph_state_list("graph_state_list/"   scene   "/"   folder   "/"   directory   "/activityList-graph-state-*.json")
            create_rdf(graph_state_list, program_description, activity_program, scene, directory)
    except Exception as e:
        print(e.args)


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Input In [66], in <cell line: 2>()
      1 scene = 'scene1'
----> 2 folders = os.listdir("graph_state_list/"   scene   "/")
      3 for folder in folders:
      4     try:

FileNotFoundError: [Errno 2] No such file or directory: 'graph_state_list/scene1/'

CodePudding user response:

The problem is with the slash character you have in your path.

Try to use this instead:

activity_directory = "graph_state_list\\"   scene   "\\"   folder

EDIT: the error is raised in line 2, so please change that one as well to:

folders = os.listdir("graph_state_list\\"   scene   "\\")

CodePudding user response:

May I suggest using os.path.join() in order to use the correct folder structure:

import os

current_dir = os.getcwd()
scene = 'scene1'
folders = os.path.join(current_dir, "graph_state_list", scene)
print(folders)
for folder in os.listdir(folders):
    ...

Result (folders):

C:\Users\xxx\OneDrive\BACKUP\Python\graph_state_list\scene1
  • Related