我面临文件未找到的问题.操作系统.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/'

推荐答案

为了使用正确的文件夹 struct ,我可以建议使用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

Python相关问答推荐

时间序列分解

ModuleNotFound错误:没有名为Crypto Windows 11、Python 3.11.6的模块

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

如何在达到end_time时自动将状态字段从1更改为0

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''

为什么在FastAPI中创建与数据库的连接时需要使用生成器?

如何在海上配对图中使某些标记周围的黑色边框

如何在Great Table中处理inf和nans

并行编程:同步进程

Python 3试图访问在线程调用中实例化的类的对象

为用户输入的整数查找根/幂整数对的Python练习

用fft计算指数复和代替求和来模拟衍射?

如何在Airflow执行日期中保留日期并将时间转换为00:00

删除Dataframe中的第一个空白行并重新索引列

文本溢出了Kivy的视区

仅取消堆叠最后三列

使用pythonminidom过滤XML文件

利用广播使减法更有效率

了解如何让库认识到我具有所需的依赖项