【问题标题】:Get the directory path of absolute file path in PythonPython中获取绝对文件路径的目录路径
【发布时间】:2023-04-05 04:56:01
【问题描述】:

我想获取文件所在的目录。例如完整路径为:

fullpath = "/absolute/path/to/file"
# something like:
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to"

我可以这样做:

dir = '/'.join(fullpath.split('/')[:-1])

但是上面的例子依赖于特定的目录分隔符,并不是很漂亮。有没有更好的办法?

【问题讨论】:

标签: python path


【解决方案1】:

你正在寻找这个:

>>> import os.path
>>> fullpath = '/absolute/path/to/file'
>>> os.path.dirname(fullpath)
'/absolute/path/to'

相关功能:

>>> os.path.basename(fullpath)
'file'
>>> os.path.split(fullpath)
('/absolute/path/to','file')

【讨论】:

  • 你为什么要import os.path而不是简单的import os
  • 我曾经认为导入os.path 不允许我导入os.anything_else(即我需要import os)。尝试时发现自己错了。
猜你喜欢
  • 1970-01-01
  • 2020-07-15
  • 2012-10-04
  • 2012-04-06
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多