【问题标题】:file directory not found in different python packages在不同的python包中找不到文件目录
【发布时间】:2019-12-06 10:01:07
【问题描述】:

我有一个项目,其结构如下所示:

Foo
|- init.py
|- xml_folder
|  - file1.xml
|- bar.py
|- tests #contains TDDs
|  - test1.py

在 bar.py 中,我将 xml_folder 中的文件列表附加到列表中:

file_list = os.listdir("xml_folder")

我正在尝试通过在 test1.py 中调用它并检查列表的大小来测试列表是否为空,这在使用绝对路径时非常有效,但是现在我使用的是相对路径,它不起作用(并且我必须使用相对路径进行发布)

调用test1.py在bar.py中追加列表的方法时抛出错误

FileNotFoundError: [Errno 2] 没有这样的文件或目录:'xml_folder'

我应该怎么做才能解决这个问题??

【问题讨论】:

  • 在使用os.listdir( )之前,您是否尝试使用os.chdir( )更改当前目录
  • 我认为他只是在其他目录中有test1.py,他只需加入文件和文件夹的路径。

标签: python directory init file-not-found


【解决方案1】:

使用 python 的pathlib 模块来处理文件系统相关的事情。

from pathlib import Path

# Below line will give you the path to the xml_folder one level up

xml_folder = Path(__file__).absolute().parents[1] / Path('xml_folder')

# Get the file name of that folder

file_list = xml_folder.glob("**/*")

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2016-07-12
    • 2016-06-16
    • 1970-01-01
    相关资源
    最近更新 更多