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

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

    Thought I would throw in a variation to the use of the os.path.splitext without the need to use array indexing.

    The function always returns a (root, ext) pair so it is safe to use:

    root, ext = os.path.splitext(path)

    Example:

    >>> import os
    >>> path = 'my_text_file.txt'
    >>> root, ext = os.path.splitext(path)
    >>> root
    'my_text_file'
    >>> ext
    '.txt'
    

提交回复
热议问题