1. 程式人生 > >python: 將列表中的字串 連線成一個 長路徑

python: 將列表中的字串 連線成一個 長路徑

  今天實習公司分配了一個數據處理的任務。在將列表中的字串連線成一個長路徑時,我遇到了如下問題:

import os

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

print os.path.join(path_list)

  發現 os.path.join 之後,依然是字串列表。這我就納悶了:

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

  細思後想明白了,os.path.join 的輸入必須是一個或多個 str ,而不能是 list 。字串列表的本質依然是list。指令把 字串列表 理解成了一個 str ,就相當於對 單str 進行 os.path.join ,最後當然沒變化啦。

  於是我修改了程式碼:

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

  終於將列表中的字串連線成了一個完整的長路徑:

first_directory/second_directory/file.txt