0

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

DiffTrav
  • 3
  • 2

2 Answers2

1

If I understood your issue correctly, the following code should help you:

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

for i in range(len(path_of_each_file)):
    print(os.path.basename(path_of_each_file[i]))

Output:

abcd.txt
efgh.txt
ijkl.txt
Md Abrar Jahin
  • 374
  • 3
  • 9
0

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)
  • use the pathlib module for portability.
  • list is the type name of a list object, not recommended to use as a variable name.
  • "/" is the operator to join Path objects.
  • using for elem in alist: ... is more pythonic.
  • np.name is the equivalent of os.path.basname(op) when using pathlib.
Doug Henderson
  • 785
  • 8
  • 17