python在哪里查找脚本中的文件?

时间:2013-03-05 05:54:37

标签: python eclipse directory pythonpath

所以我刚刚将这个类编写为标题屏幕并且效果很好。但是,我正在与该项目合作的人之一提到我不应该使用:

os.chdir(os.getcwd() + "/..")

resource = (os.getcwd() + "/media/file name")

进入超级目录。他确实提到了关于pythonpath的一些事情。如果这有一些帮助,我们正在使用Eclipse。

对于更多上下文,我们正在制作一个多平台游戏,所以我们不能只是同步我们的目录并对其进行硬编码(虽然我们使用git,因此工作目录是同步的)。基本上,我需要一些方法从“src”文件夹中的脚本文件到它旁边的“media”文件夹(AKA有一个超级(项目)文件夹,其中包含“src”和“media”文件夹)

任何帮助都会非常感激,但请不要说“google it”因为我在来之前尝试过(我不知道这是否经常发生,但我在其他地方看过很多次) ......当我用谷歌搜索答案时,对不起,如果我发出嘶嘶声说话那就好了)

3 个答案:

答案 0 :(得分:2)

Python程序确实具有当前工作目录的概念,它通常是运行脚本的目录。这是“他们寻找文件的地方”,带有相对路径。

但是,由于您的程序可以从与中的文件夹不同的文件夹运行,因此您的引用目录需要引用您的脚本所在的目录(通常,当前目录与脚本的位置相关)。使用

获取找到脚本的目录
script_dir = os.path.dirname(__file__)

请注意,此路径可以是相对的(可能为空),因此脚本的当前工作目录与python解释器读取脚本时的目录(即{{1已设置)。如果稍后在代码中更改当前工作目录,则将可能相对__file__转换为绝对路径非常重要:

script_dir

然后,您可以使用与平台无关的

访问父目录中的目录# If script_dir is relative, the current working directory is used, here. This is correct if the current # working directory is the same as when the script was read by the Python interpreter (which is # when __file__ was set): script_dir = os.path.abspath(script_dir)
media

实际上os.path.join(script_dir, os.path.pardir, 'media') (或等效os.path.pardir)是与平台无关的父目录约定,os.pardir只是以独立于平台的方式加入路径。

答案 1 :(得分:1)

我建议像:

import os.path

base_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
media_folder = os.path.join(base_folder, "media")
src_folder = os.path.join(base_folder, "src")

resource = os.path.join(media_folder, "filename")

for path in [base_folder, media_folder, src_folder, resource]:
    print path

主要成分是:

  • __file__:获取当前源文件的路径(与sys.argv[0]不同,后者给出了被调用脚本的路径)
  • os.path.split():将路径拆分为相对文件/文件夹名称和包含它的基本文件夹。在base_folder = ...中使用它两次将给出父目录。
  • os.path.join:与操作系统无关且路径名正确的组合。知道缺少或多个/\ s

答案 2 :(得分:0)

考虑使用os.path.dirname()os.path.join()。这些应该以独立于平台的方式工作。

相关问题