我可以
>>> os.path.join("c:/","home","foo","bar","some.txt")
'c:/home\\foo\\bar\\some.txt'
但是,当我这样做
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(s)
['c:/', 'home', 'foo', 'bar', 'some.txt']
我在这里想念什么?
Answers:
问题是,os.path.join
不接受list
as参数,它必须是单独的参数。
在这里*
,“ splat”运算符开始起作用...
我可以
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
假设join
不是按照这种方式设计的(正如ATOzTOA所指出的那样),并且只采用了两个参数,您仍然可以使用内置参数reduce
:
>>> reduce(os.path.join,["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt'
相同的输出,如:
>>> os.path.join(*["c:/","home","foo","bar","some.txt"])
'c:/home\\foo\\bar\\some.txt'
仅出于完整性和教育方面的原因(以及其他*
无法正常工作的情况)。
Python 3提示
reduce
已移至functools
模块。
reduce
中functools
,如果有人像我一样正在寻找它,则将其移至模块。
reduce
到模块是一个声明。
from functools import reduce
这只是方法。您什么都不会错过。在官方文件显示,你可以用列表拆包提供几条路径:
s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)
注意in中的*s
intead 。使用星号将触发列表的解压缩,这意味着每个列表参数将作为单独的参数提供给函数。s
os.path.join(*s)