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

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

    Getting the name of the file without the extension:

    import os
    print(os.path.splitext("/path/to/some/file.txt")[0])
    

    Prints:

    /path/to/some/file
    

    Documentation for os.path.splitext.

    Important Note: If the filename has multiple dots, only the extension after the last one is removed. For example:

    import os
    print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
    

    Prints:

    /path/to/some/file.txt.zip
    

    See other answers below if you need to handle that case.

提交回复
热议问题