os.path.join() 的简短方法

Vas*_*ily 1 python python-2.7 python-3.x os.path

我真的厌倦了os.path.join()每次必须构建一条路径时都要打字,我正在考虑定义一个像这样的快捷方式:

def pj(*args):
    from os.path import join
    return join(args)
Run Code Online (Sandbox Code Playgroud)

但它抛出TypeError: join() argument must be str or bytes, not 'tuple'

所以我想知道传递参数的正确方法是什么os.path.join(),总而言之,我是否试图重新发明轮子?

Mos*_*oye 5

您应该将参数解压缩.join为:

join(*args)
#    ^
Run Code Online (Sandbox Code Playgroud)

就像这样:

>>> import os.path.join
>>> args = ('/usr/main/', 'etc/negate/')
>>> os.path.join(*args)
'/usr/main/etc/negate/'
Run Code Online (Sandbox Code Playgroud)

PS:import在你的函数中使用并不是一个好主意。将其移至模块的顶部。


Fel*_*lix 5

如果您使用的是 Python 3.4,您可以尝试一下pathlib 。

来自文档:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
Run Code Online (Sandbox Code Playgroud)