python concatenates strings in a list into a long path

  • 2020-12-26 05:47:56
  • OfStack

Today, the internship company assigned a data processing task. When concatenating strings from a list into a long path, I ran into the following problem:


import os

path_list = ['first_directory', 'second_directory', 'file.txt']

print os.path.join(path_list)

After you find os.path.join, you still have a list of strings. And I wondered:


['first_directory', 'second_directory', 'file.txt']

On reflection, it became clear that the input to os.path.join must be one or more str, not list. The essence of the string list is still list. The instruction interprets the list of strings as one str, which is the same as os.path.join for a single str, but of course it doesn't change.

So I changed the code:


import os

path_list = ['first_directory', 'second_directory', 'file.txt']

# print os.path.join(path_list)

head = ''
for path in path_list:
 head = os.path.join(head, path)
print head

Finally, the string in the list is concatenated into a full long path:


first_directory/second_directory/file.txt

Related articles: