【问题标题】:os.path.join(os.path.dirname(__file__)) returns nothingos.path.join(os.path.dirname(__file__)) 什么都不返回
【发布时间】:2012-06-12 18:57:42
【问题描述】:

我有一个这样的目录结构:

--bin/
--lib/
--data/

所以基本上,可执行脚本在 bin 中,它调用 lib 中的文件.. 但 lib 必须与 data 中的文本文件通信

通常这种用法可以工作: 要读取文件,我通常会这样做

file_path =  os.path.join(os.path.dirname(__file__))+ "/../" +"data/"+filename
f = open(file_path,"r")

但是,在这种情况下,如果我这样做:

  print os.path.join(os.path.dirname(__file__))
  returns nothing?

我做错了什么.. 谢谢

【问题讨论】:

  • 能否举个例子说明__文件__的具体内容

标签: python


【解决方案1】:

我猜 nothing 你的意思是一个空字符串?只有当__file__ 最初是一个空字符串时,才会出现这种情况。您是否不小心覆盖了__file__

【讨论】:

  • 我不确定,我很明白...(对不起.. 还在学习这一切).. 有两个文件,file1.py 在那里我正在读取一个文件.. 它可以工作..然后在file2.py(在file1.py之后读取)我做同样的事情..但它返回空字符串
  • 嘿..谢谢..它有效..我的坏..我正在这样做。 filepath = os.path.join(os.path.dirname(file))+ "/../" +"data/"+filename 所以它返回一个 null.. 作为文件名和然后 +"/.." 意味着将 cding 为 null 我认为 :) 谢谢
【解决方案2】:

除了其他评论之外还有其他评论...os.path.join 的重点是避免类似

mypath=dir + '/' + subdir + '/'+filename

这使用起来更干净

mypath=os.path.join(dir,subdir,filename) # can have as many arguments as you want!

此外,您可以避免显式的“..”和“.”在路径名中使用os.pardiros.curdir。 (例如)

file_path =  os.path.join(os.path.dirname(__file__),os.pardir,'data',filename)

这应该会增加代码的可移植性(即使您不打算在其他任何地方运行此脚本,也是一个养成的好习惯)。

【讨论】:

    【解决方案3】:

    这取决于您如何启动脚本,例如:

    如果/bin/script.py 包含:

    import os
    print os.path.dirname(__file__)   #no reason to use os.path.join()
    

    然后:

    $> python /bin/script.py
    /bin
    $> cd /bin
    $> python script.py
                           #nothing
    $>
    

    最好使用以下方法:

    file_path = os.path.abspath(__file__)
    

    然后做任何你想做的事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多