filepathpython-2.6os.path

Join elements of a list into a path


I've got a list and I need to join th elements to form a path. os.join.path does not seem to work. The list is obtianed as:

    file_path.split("\\")[:-1]

this returns:

    ['L:', 'JM6', 'jm6', 'test', 'turb', 'results', 'v6.2', 'examples']

Using:

   print(os.path.join(file_path.split("\\")[:-1]))

returns exactly the same list without joining it into a path:

    ['L:', 'JM6', 'jm6', 'test', 'turb', 'results', 'v6.2', 'examples']

Using:

   print(os.path.join(os.path.sep, file_path.split("\\")[:-1]))

returns the error:

   print(os.path.join(os.path.sep, file_path.split("\\")[:-1]))
   File "C:\Python\lib\ntpath.py", line 73, in join
      elif isabs(b):
   File "C:\Python\lib\ntpath.py", line 58, in isabs
      return s != '' and s[:1] in '/\\'
 TypeError: 'in <string>' requires string as left operand, not list

Thanks


Solution

  • os.path.join() doesn't take a list as argument, it takes several arguments.

    using * (the 'splat' operator) should work:

    list=['L:', 'JM6', 'jm6', 'test', 'turb', 'results', 'v6.2', 'examples']
    os.path.join(*list)