父文件夹脚本 FileNotFoundError

Parent folder script FileNotFoundError

我的 Python 应用程序包含一个名为 Tests 的子文件夹,我用它来进行 运行 单元测试。我的所有文件都在父文件夹中,我将其称为 App。 Tests 文件夹包含一个 test.py 文件。 App 文件夹包含一个 app.py 文件和一个 file.txt 文本文件。

在我的 test.py 文件中,我可以这样导入:

import sys
sys.path.append("PATH_TO_PARENT_DIR")

假设我的 app.py 文件包含以下内容:

class Stuff():
    def do_stuff():
        with open("file.txt") as f:
            pass

现在如果我 运行 test.py,我得到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

我该如何解决这个问题?非常感谢!

open 函数在 与调用 open 函数的脚本 相同的文件夹中查找文件。因此,您的 test.py 会在 tests 文件夹中查找,而不是在 app 文件夹中。您需要添加文件的完整路径。

open('app_folder' + 'text.txt')

或将 test.py 文件移动到与 text.txt

相同的文件夹中

假设该文件与您的脚本位于同一文件夹中:

import os
parent_dir = os.path.abspath(os.path.dirname(__file__))
class Stuff():
    def do_stuff():
        with open(os.path.join(parent_dir, "file.txt")) as f:
            pass

解释:

__file__ 是你脚本的路径

os.path.dirname 获取脚本所在的目录

os.path.abspath 使该路径成为绝对路径而不是相对路径(以防相对路径弄乱你的脚本,这是一个好习惯)

然后我们需要做的就是将您的 parent_dir 与文件合并,我们使用 os.path.join.

在此处阅读有关 os.path 方法的文档:https://docs.python.org/3/library/os.path.html

此代码的更明确的版本可以这样写,如果有帮助的话:

import os
script_path = __file__
parent_dir = os.path.dirname(script_path)
parent_dir_absolute = os.path.abspath(parent_dir)
path_to_txt = os.path.join(parent_dir_absolute, 'file.txt')