FileNotFoundError使用os.listdir()时发生竞回错误(最近的调用在最后)

zzlelutf  于 2022-11-02  发布在  其他
关注(0)|答案(3)|浏览(204)

我遇到了一个文件找不到的问题。操作系统。listdir()方法应该能够加载文件夹。为什么它不能正常工作?请给我任何意见和建议。谢谢。

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/'
ig9co6j1

ig9co6j11#

问题出在路径中的斜线字符。
请尝试使用以下代码:

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

EDIT:第2行出现错误,因此请将该行也更改为:

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

mwg9r5ms2#

我建议使用os.path.join(),以便使用正确的文件夹结构:

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):
    ...

结果(文件夹):

C:\Users\xxx\OneDrive\BACKUP\Python\graph_state_list\scene1
5n0oy7gb

5n0oy7gb3#

您应该使用双斜线编写完整路径,如:
C:\\Users\\user name\\jupyter\\circle\\rect\\images

相关问题