Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 操作os.path.join()的捷径_Python_Python 2.7_Python 3.x_Os.path - Fatal编程技术网

Python 操作os.path.join()的捷径

Python 操作os.path.join()的捷径,python,python-2.7,python-3.x,os.path,Python,Python 2.7,Python 3.x,Os.path,我真的厌倦了每次必须构建路径时键入os.path.join,我想定义一个如下的快捷方式: def pj(*args): from os.path import join return join(args) 但它抛出TypeError:连接参数必须是str或bytes,而不是“tuple” 因此,我想知道什么是将参数传递给os.path.join的正确方法,总之,我是在试图重新发明轮子吗 您应该将参数解压缩到。join: 像这样: >>> import os.p

我真的厌倦了每次必须构建路径时键入os.path.join,我想定义一个如下的快捷方式:

def pj(*args):
    from os.path import join
    return join(args)
但它抛出TypeError:连接参数必须是str或bytes,而不是“tuple”

因此,我想知道什么是将参数传递给os.path.join的正确方法,总之,我是在试图重新发明轮子吗

您应该将参数解压缩到。join:

像这样:

>>> import os.path.join
>>> args = ('/usr/main/', 'etc/negate/')
>>> os.path.join(*args)
'/usr/main/etc/negate/'

附言:在函数中使用导入不是一个好主意。将其移动到模块顶部。

如果您使用的是Python 3.4,您可以试一试

从文档:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')

您可以在import语句中重命名它:

from os.path import join as pj # or whatever other name you pick 
                               # to distinguish it from str.join

您不应该在函数内部导入。为什么不直接从os.path导入连接到您使用它的任何地方?那么就不必键入os.path。它只长了两个字母,更不用说更具可读性,而且更可能是任何阅读您的代码的人都已经知道的东西。当您导入助手函数时,它仍然会被执行。@matthiaschreiber是的,它可以。这取决于人们对这种简短形式的熟悉程度:numpy->np,pandas->pd,为什么不。
from os.path import join as pj # or whatever other name you pick 
                               # to distinguish it from str.join