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

前端 未结 23 1501
逝去的感伤
逝去的感伤 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
    >>> print(os.path.splitext(os.path.basename("/path/to/file/hemanth.txt"))[0])
    hemanth
    
    0 讨论(0)
  • 2020-11-22 06:46

    In Python 3.4+ you can use the pathlib solution

    from pathlib import Path
    
    print(Path(your_path).resolve().stem)
    
    0 讨论(0)
  • 2020-11-22 06:47

    the easiest way to resolve this is to

    import ntpath 
    print('Base name is ',ntpath.basename('/path/to/the/file/'))
    

    this saves you time and computation cost.

    0 讨论(0)
  • 2020-11-22 06:50

    Using pathlib in Python 3.4+

    from pathlib import Path
    
    Path('/root/dir/sub/file.ext').stem
    

    will return

    'file'
    
    0 讨论(0)
  • 2020-11-22 06:50

    import os

    filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv
    

    This returns the filename without the extension(C:\Users\Public\Videos\Sample Videos\wildlife)

    temp = os.path.splitext(filename)[0]  
    

    Now you can get just the filename from the temp with

    os.path.basename(temp)   #this returns just the filename (wildlife)
    
    0 讨论(0)
提交回复
热议问题