How to get the filename without the extension from a path in Python?

前端 未结 23 1878
逝去的感伤
逝去的感伤 2020-11-22 05:43

How to get the filename without the extension from a path in Python?

For instance, if I had "/path/to/some/file.txt", I would want "

23条回答
  •  耶瑟儿~
    2020-11-22 06:41

    For convenience, a simple function wrapping the two methods from os.path :

    def filename(path):
      """Return file name without extension from path.
    
      See https://docs.python.org/3/library/os.path.html
      """
      import os.path
      b = os.path.split(path)[1]  # path, *filename*
      f = os.path.splitext(b)[0]  # *file*, ext
      #print(path, b, f)
      return f
    

    Tested with Python 3.5.

提交回复
热议问题