【问题标题】:Short way to do os.path.join()做 os.path.join() 的捷径
【发布时间】:2016-06-22 12:18:30
【问题描述】:

每次我必须构造一条路径时,我真的厌倦了输入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() 的正确方法是什么,总而言之,我是在尝试重新发明轮子吗?

【问题讨论】:

  • 你不应该在函数内部import。为什么不只是 from os.path import join 无论您在哪里使用它?然后你不必输入os.path.,它只长了两个字母(更不用说更具可读性,更有可能是任何阅读你代码的人都知道的东西)。
  • 我会将导入放在函数之外。当你导入你的辅助函数时,它会被执行。

标签: python python-2.7 python-3.x os.path


【解决方案1】:

你应该解压.join的参数:

join(*args)
#    ^

像这样:

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

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

【讨论】:

  • @MatthiasSchreiber 是的,它可以。取决于人们对这种简短形式的熟悉程度:numpy -> nppandas -> pd,为什么不呢。
【解决方案2】:

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

来自文档:

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

【讨论】:

    【解决方案3】:

    你可以在import语句中重命名:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2011-12-13
      • 1970-01-01
      相关资源
      最近更新 更多