如何使用python从另一个cwd获取文件的绝对路径

2024-05-03 22:29:05 发布

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

我正在从以下目录运行Python脚本:

/user/home/test_script.py

此脚本获取以下目录中的文件名:

/user/folder1/folder2/folder3/this_file.py

因此在test_script.py中,我最终得到一个包含this_file.py的变量。我需要获得this_file.py的绝对路径才能在脚本中继续运行。换句话说,我需要/user/folder1/folder2/folder3/this_file.py

我看过一些论坛和帖子,但运气不太好。使用带有resolve()方法的pathlib Path模块似乎试图将我的cwd附加到this_file.py的开头

我得到的是:

# This is `test_script.py`

from pathlib import Path

# <function that parses a file and returns `this_file.py`>
foundFile = "./this_file.py"

# I try to make the path absolute
p = Path(foundFile).resolve()

我得到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'user/home/this_file.py'

编辑: 我可以从搜索方法中获取路径,然后将带有文件名的路径传递给下一个方法。然而,我正在寻找的是一种不必单独搜索路径就可以获得路径的方法