python中如何将列表中的字符串连接成一个长路径的实例

黄舟
黄舟 原创
2017-10-07 11:41:17 1858浏览

今天实习公司分配了一个数据处理的任务。在将列表中的字符串连接成一个长路径时,我遇到了如下问题:

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

以上就是python中如何将列表中的字符串连接成一个长路径的实例的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。