【问题标题】:How to get the full path of a file in python including the subdirectory?如何在python中获取文件的完整路径,包括子目录?
【发布时间】:2022-01-03 15:38:36
【问题描述】:

我尝试了所有方法,但它根本不起作用。我有一个位于子目录中的文件,并且该子目录位于目录中。调用类似的东西

os.path.abspath(__file__))

只产生

directory\\file

但我需要

directory\\subdirectory\\file

应该有一个简单的方法来做到这一点,对吧?我不知道为什么 abspath 无法识别子目录。

【问题讨论】:

  • 您能粘贴用于将文件对象分配给变量的代码吗?

标签: python directory path operating-system


【解决方案1】:
from pathlib import Path

my_path = Path("my_file.txt")
full_path = Path.resolve()

然后,如果需要,您可以将 full_path 转换为字符串。

【讨论】:

    【解决方案2】:

    你应该看看pathlib module

    【讨论】:

    • 哪种方法?我在那里找不到任何有用的东西。
    猜你喜欢
    • 2013-11-12
    • 2016-01-17
    • 2022-07-28
    • 2014-04-18
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    相关资源
    最近更新 更多