python-3.xstringlistcygwinbasename

Extracting basename from a a string with mixed slashes


I am trying to extract the basename abcd.txt from the following, which I am getting from a join operation performed on a list :

path = "my/python/is/working"
list = ["abcd","efgh","ijkl"]
path_of_each_file = [path + "\\" + x for x in list]

Therefore the list looks like :

path[0] = ["my/python/is/working\\abcd.txt","my/python/is/working\\abcd.txt","my/python/is/working\\abcd.txt"]

I am using the following to get the base name from each ekement of the list :

name_base = os.path.basename(path[0])

But the output which I get is :

name_base = working\\abcd.txt

I just need abcd.txt as my base name.

Thanks in advance


Solution

  • The modern way:

    from pathlib import Path
    path = Path("my/python/is/working")
    flist = ["abcd.txt","efgh.txt","ijkl.txt"]
    path_of_each_file = [path / x for x in flist]
    
    for p in path_of_each_file:
        print(p.name)