做 os.path.join() 的捷径
Short way to do os.path.join()
我真的厌倦了每次必须构建路径时都输入 os.path.join()
,我正在考虑定义一个这样的快捷方式:
def pj(*args):
from os.path import join
return join(args)
但是它抛出 TypeError: join() argument must be str or bytes, not 'tuple'
所以我想知道将参数传递给 os.path.join()
的正确方法是什么,总而言之,我是在重新发明轮子吗?
您应该解压缩 .join
:
的参数
join(*args)
# ^
像这样:
>>> import os.path.join
>>> args = ('/usr/main/', 'etc/negate/')
>>> os.path.join(*args)
'/usr/main/etc/negate/'
P.S.: 在你的函数中使用 import
不是一个好主意。将其移至模块顶部。
如果您使用的是 Python 3.4,可以尝试 pathlib。
来自文档:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
可以在导入语句中重命名:
from os.path import join as pj # or whatever other name you pick
# to distinguish it from str.join
我真的厌倦了每次必须构建路径时都输入 os.path.join()
,我正在考虑定义一个这样的快捷方式:
def pj(*args):
from os.path import join
return join(args)
但是它抛出 TypeError: join() argument must be str or bytes, not 'tuple'
所以我想知道将参数传递给 os.path.join()
的正确方法是什么,总而言之,我是在重新发明轮子吗?
您应该解压缩 .join
:
join(*args)
# ^
像这样:
>>> import os.path.join
>>> args = ('/usr/main/', 'etc/negate/')
>>> os.path.join(*args)
'/usr/main/etc/negate/'
P.S.: 在你的函数中使用 import
不是一个好主意。将其移至模块顶部。
如果您使用的是 Python 3.4,可以尝试 pathlib。
来自文档:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
可以在导入语句中重命名:
from os.path import join as pj # or whatever other name you pick
# to distinguish it from str.join