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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值