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

前端 未结 23 1910
逝去的感伤
逝去的感伤 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条回答
  •  Happy的楠姐
    2020-11-22 06:34

    The other methods don't remove multiple extensions. Some also have problems with filenames that don't have extensions. This snippet deals with both instances and works in both Python 2 and 3. It grabs the basename from the path, splits the value on dots, and returns the first one which is the initial part of the filename.

    import os
    
    def get_filename_without_extension(file_path):
        file_basename = os.path.basename(file_path)
        filename_without_extension = file_basename.split('.')[0]
        return filename_without_extension
    

    Here's a set of examples to run:

    example_paths = [
        "FileName", 
        "./FileName",
        "../../FileName",
        "FileName.txt", 
        "./FileName.txt.zip.asc",
        "/path/to/some/FileName",
        "/path/to/some/FileName.txt",
        "/path/to/some/FileName.txt.zip.asc"
    ]
    
    for example_path in example_paths:
        print(get_filename_without_extension(example_path))
    

    In every case, the value printed is:

    FileName
    

提交回复
热议问题