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

前端 未结 23 1510
逝去的感伤
逝去的感伤 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:29

    We could do some simple split / pop magic as seen here (https://stackoverflow.com/a/424006/1250044), to extract the filename (respecting the windows and POSIX differences).

    def getFileNameWithoutExtension(path):
      return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]
    
    getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
    # => file-0.0.1
    
    getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
    # => file-0.0.1
    

提交回复
热议问题