【问题标题】:How to open a file in the parent directory in python in AppEngine?如何在AppEngine中的python中打开父目录中的文件?
【发布时间】:2010-05-02 11:09:40
【问题描述】:

如何在 AppEngine 中的 python 中打开父目录中的文件?

我有一个 python 文件 module/mod.py,代码如下

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。

有解决办法吗?

【问题讨论】:

    标签: python google-app-engine


    【解决方案1】:

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

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

    【讨论】:

    • 在我看来,最好不要连接文件名,而是使用“os.path.join” 例如: open(os.path.join(os.path.dirname( 文件), os.pardir, 'data.yml'))
    • 是的。但请确保使用 _file_ 而不是 file
    • 或者,确保将code 包含在反引号中。
    • 这对我不起作用。它查找带有 /../ 组件的路径。错误是 FileNotFoundError: [Errno 2] No such file or directory: '/brownie/scripts/../brownie-config.yml'
    【解决方案2】:

    遇到这个问题并且对答案不满意,我遇到了不同的解决方案。花了以下时间才得到我想要的。

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

      current_directory = os.path.dirname(__file__)

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

      parent_directory = os.path.split(current_directory)[0] # Repeat as needed

    3. 将 parent_directory 与任何子目录连接:

      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')
    

    【讨论】:

      【解决方案3】:

      ?? 替代解决方案 ??

      您也可以使用sys 模块获取当前工作目录。
      因此,做同样事情的另一种选择是:

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

      【讨论】:

        【解决方案4】:

        我写了一个名为 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('/')
        

        【讨论】:

        • 使用os.path.dirname或类似的专门功能更正确,不要自己重新发明它们。更正确的加入字符串的方法是'/'.join(list)
        【解决方案5】:

        @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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-10
          • 1970-01-01
          • 1970-01-01
          • 2012-04-22
          • 2014-11-21
          • 1970-01-01
          • 1970-01-01
          • 2018-07-07
          相关资源
          最近更新 更多