【问题标题】:Path to a file without basename [duplicate]没有基本名称的文件的路径[重复]
【发布时间】:2012-08-01 10:42:25
【问题描述】:

如何获取没有文件基名的文件路径?

类似/a/path/to/my/file.txt --> /a/path/to/my/

尝试使用.split() 没有成功。

【问题讨论】:

    标签: python


    【解决方案1】:

    使用os.path.dirname(filename)

    【讨论】:

      【解决方案2】:

      你可以import os

      >>> filepath
      '/a/path/to/my/file.txt'
      >>> os.path.dirname(filepath)
      '/a/path/to/my'
      >>> 
      

      【讨论】:

        【解决方案3】:
        (dirname, filename) = os.path.split(path)
        

        【讨论】:

        • 更准确地说:(rest, first_path_item) = os.path.split(path)
        【解决方案4】:

        检查os.path的订阅者

        os.path.dirname('/test/one')
        

        【讨论】:

          【解决方案5】:

          从 Python 3.4 开始,您可以使用 Pathlib。

          from pathlib import Path
          
          path = Path("/a/path/to/my/file.txt")
          print(path.parent)
          

          【讨论】:

            猜你喜欢
            • 2011-02-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-16
            • 2014-07-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多