Get Filename Without Extension in Python

前端 未结 5 1302
北海茫月
北海茫月 2021-02-01 00:26

If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex b

相关标签:
5条回答
  • 2021-02-01 00:33
    >>> import os
    >>> os.path.splitext("1.1.1.1.1.jpg")
    ('1.1.1.1.1', '.jpg')
    
    0 讨论(0)
  • 2021-02-01 00:35

    No need for regex. os.path.splitext is your friend:

    os.path.splitext('1.1.1.jpg')
    >>> ('1.1.1', '.jpg')
    
    0 讨论(0)
  • 2021-02-01 00:36

    If I had to do this with a regex, I'd do it like this:

    s = re.sub(r'\.jpg$', '', s)
    
    0 讨论(0)
  • 2021-02-01 00:37

    You can use stem method to get file name.

    Here is an example:

    from pathlib import Path
    
    p = Path(r"\\some_directory\subdirectory\my_file.txt")
    print(p.stem)
    # my_file
    
    0 讨论(0)
  • 2021-02-01 00:39

    In most cases, you shouldn't use a regex for that.

    os.path.splitext(filename)[0]
    

    This will also handle a filename like .bashrc correctly by keeping the whole name.

    0 讨论(0)
提交回复
热议问题