【问题标题】:Change directory to the directory of a Python script [duplicate]将目录更改为 Python 脚本的目录 [重复]
【发布时间】:2010-10-05 07:34:52
【问题描述】:

如何将目录更改为包含我的 python 脚本的目录?到目前为止,我发现我应该使用os.chdirsys.argv[0]。我确信有更好的方法来编写我自己的函数来解析 argv[0]。

【问题讨论】:

标签: python scripting directory


【解决方案1】:
os.chdir(os.path.dirname(__file__))

【讨论】:

  • 出于某种原因 file 是 C:\dev\Python25\Lib\idlelib 所以用 argv[0] 快速替换解决了它。 +1 并勾选标记
  • 另外,根据平台,您可能希望在 os.path.dirname 的结果上使用 os.path.abspath 以确保任何符号链接或其他文件系统重定向得到正确扩展。
【解决方案2】:

os.chdir(os.path.dirname(os.path.abspath(__file__))) 应该这样做。

如果脚本从它所在的目录运行,os.chdir(os.path.dirname(__file__)) 将不起作用。

【讨论】:

  • os.chdir(os.path.dirname(__file__) or '.')也可以。当__file__ 没有以./ 为前缀时,就会出现目录内问题。 os.path.dirname 在这种情况下返回一个空字符串。
  • 很好的观察@George :)
【解决方案3】:

有时__file__没有定义,这种情况你可以试试sys.path[0]

【讨论】:

  • @Miki - __file__ 什么时候没有定义?
  • @RobBednark: python3.3 -c "print(__file__)"
  • @JanusTroelsen:Python 2.7 也是如此。
【解决方案4】:

在 Windows 操作系统上,如果你调用类似 python somefile.py 这个 os.chdir(os.path.dirname(__file__)) 会抛出一个 WindowsError。但这应该适用于所有情况:

import os
absFilePath = os.path.abspath(__file__)
os.chdir( os.path.dirname(absFilePath) )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 2014-04-12
    • 1970-01-01
    • 2017-04-01
    • 2011-09-28
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    相关资源
    最近更新 更多