Search code examples
python-3.xos.path

os.path.basename(file) vs file.split("/")[-1]


I need to extract seq_00034 from a file path like

    file = "/home/user/workspace/data/seq_00034.pkl"

I know 2 ways to achieve it:

method.A

    import os
    seq_name = os.path.basename(file).split(".")[0]

or

method.B

    seq_name = file.split("/")[-1].split(".")[0]

Which is safer/faster?

(taking the cost of import os into account)

Is there a more elegent way to extract seq_name from given path?


Solution

  • I think the more elegant way would be by using the pathlib.Path.stem() method

    import pathlib
    
    filename =  "/home/user/workspace/data/seq_00034.pkl"
    path = pathlib.Path(filename)
    
    print(path.stem)