如何在AppEngine中使用Python打开父目录中的文件?

33

如何在AppEngine中使用Python打开父目录中的文件?

我有一个名为module/mod.py的Python文件,其中包含以下代码:

f = open('../data.yml')
z = yaml.load(f)
f.close()

data.yml文件在模块的上一级目录中。我遇到的错误是:

IOError: [Errno 13] file not accessible: '../data.yml'

我正在使用AppEngine SDK 1.3.3。

这个有什么解决办法吗?

5个回答

55

open函数的操作是相对于当前进程工作目录,而不是调用它的模块。如果路径必须是相对于模块的,请按照以下方式执行:

import os.path
f = open(os.path.dirname(__file__) + '/../data.yml')

6
我认为,如果您使用" os.path.join "而不是连接文件名,会更好。例如: open(os.path.join(os.path.dirname(file), os.pardir, 'data.yml')) - ThatsAMorais
是的。但请确保使用__file__而不是file。 - sthiers
1
请确保将 code 用反引号包裹起来。 - Marcelo Cantos
这对我不起作用。它寻找带有 /../ 组件的路径。错误是 FileNotFoundError: [Errno 2] No such file or directory: '/brownie/scripts/../brownie-config.yml'。 - tonisives

11

在遇到这个问题并对答案不满意后,我发现了一个不同的解决方案。要达到我想要的结果,需要进行以下步骤:

  1. 使用 os.path.dirname 确定当前目录:

    current_directory = os.path.dirname(__file__)

  2. 使用 os.path.split 确定父目录:

    parent_directory = os.path.split(current_directory)[0] # 如有必要,请重复执行

  3. 将父目录与任何子目录连接起来:

    file_path = os.path.join(parent_directory, 'path', 'to', 'file')

  4. 打开文件:

    open(file_path)

组合在一起:

open(os.path.join(os.path.split(os.path.dirname(__file__))[0], 'path', 'to', 'file')

5

替代方案

你也可以使用 sys 模块来获取当前工作目录。
因此,另一个实现相同功能的替代方案为:

import sys
f = open(sys.path[0] + '/../data.yml')

1
我写了一个名为get_parent_directory()的小函数,可以帮助获取父目录的路径:
import sys
def get_parent_directory():
    list = sys.path[0].split('/')[:-1]
    return_str = ''
    for element in list:
        return_str += element + '/'
    return return_str.rstrip('/')

1
更加正确的做法是使用os.path.dirname或类似的专用函数,而不是自己重新发明它们。另外,连接字符串的更正确的方式是'/'.join(list) - ont.rif

0

@ThatsAmorais的答案在一个函数中

import os

def getParent(path: str, levels=1) -> str:
    """
    @param path: starts without /
    @return: Parent path at the specified levels above.
    """
    current_directory = os.path.dirname(__file__)

    parent_directory = current_directory
    for i in range(0, levels):
        parent_directory = os.path.split(parent_directory)[0]

    file_path = os.path.join(parent_directory, path)
    return file_path

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接