无法求解文件的相对路径

2024-06-30 07:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

显然,python接受与第一个被调用文件相关的所有导入

我有以下文件结构

src
 |--myunittests.py
 |--subfolder1
      |--__init__.py
      |--printFileContent.py
      |--subfolder2
           |--__init__.py
           |--file

myunittests.py将测试printFileContent中函数的行为:

from subfolder1.printFileContent import printFileContent
printFileContent()

printFileContent打印子文件夹中包含的文件的内容:

def printFileContent():
with open("./subfolder2/file") as file:
    for line in file:
        print(line)


if __name__ == "__main__":
    printFileContent()

文件只包含一些文本

问题: 在子文件夹1中执行python3 printFileContent.py将正确输出文件内容。 但是执行python3 myunittests.py会产生错误,即找不到文件

有办法解决这个问题吗(有没有办法告诉python,以编程方式引用的相对文件应该与它们所使用的文件相对

约束

  • 更改printFileContent.py内的内容不是选项(生成的文件)
  • 这种对printFileContent的调用在整个代码中的任意位置(unittest文件调用一个对话框,该对话框在子目录2中调用printFileContent vv)

这种行为何时发生file是在printFileContent.py内使用的图标时,从myunittests.py调用printFileContent.py

次要问题: 是否有合适的标题/公告词来解释/发现这种行为及其问题


Tags: 文件py文件夹内容initline结构python3
1条回答
网友
1楼 · 发布于 2024-06-30 07:25:15

如果无法修改printFileContent.py,可以保存当前目录,转到subfolder1目录,然后返回原始目录:

import subfolder1
import os

# Save current directory (absolute path)
cdir = os.path.abspath(os.path.curdir)

# Change directory, and call printFileContent
os.chdir(os.path.dirname(subfolder1.__file__))
subfolder1.printFileContent()

# Go back to the original directory
os.chdir(cdir)

如果您必须经常使用这个方法,您可以使用with语句使这个行为成为一个可用的类,这样它更易于使用并且更健壮(您不会忘记chdir返回):

import os

class TmpDirChanger:
  def __init__(self, tmpPath):
    self.currentDir = os.path.abspath(os.path.curdir)
    os.chdir(tmpPath)

  def __enter__(self): pass

  def __exit__(self, exc_type, exc_val, exc_tb):
    #change back to original dir
    os.chdir(self.currentDir)

with TmpDirChanger('path/to/some/dir'):
   do_something()

如果可以修改printFileContent.py,那么就不那么麻烦了:

import os

def printFileContent():
    # This will give you path to subfolder1
    sfolder1 = os.path.dirname(__file__)

    # This will give you path to "file" in subfolder2
    name = os.path.join(sfolder1, 'subfolder2', 'file')

    with open(name) as file:
        for line in file:
            print(line)

相关问题 更多 >