Skip to main content
 首页 » 编程设计

python之文件的相对路径没有得到解决

2024年10月01日8birdshome

显然,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() 

文件只包含一些文本。

问题: 在 subfolder1 中执行 python3 printFileContent.py 将正确输出文件内容。 但是执行 python3 myunittests.py 会引发错误,找不到文件。

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

约束

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

此行为何时发生? 当 file 是在 printFileContent.py 中使用的图标时,而 printFileContent.py 是从 myunittests.py 中调用的

附带问题: 是否有适当的标题/要点词来解释/找出这种行为及其问题?

请您参考如下方法:

如果不能修改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)