【问题标题】:How to get python to know what directory you're working in如何让python知道你正在工作的目录
【发布时间】:2014-01-13 21:51:41
【问题描述】:

我编写了一个程序,它遍历目录中的所有文件并查找带有标志的文件,然后将它们输入到不同的程序中。它工作得很好,我现在唯一要做的就是将脚本放在盒子上的一个位置,然后让它知道在我当前所在的目录中查找工作目录。目前我所做的只是将脚本 mv 到我正在工作的任何目录中,然后从那里调用它,但这很乏味,需要我不断地 cp'ing 脚本。

我只是希望有一种更优雅的方式来做到这一点?任何帮助,将不胜感激。

【问题讨论】:

    标签: python module directory chdir working-directory


    【解决方案1】:

    怎么样

    import os
    
    loc = os.getcwd()
    

    【讨论】:

      【解决方案2】:

      __文件__对象可以返回这样的信息:

      import os
      
      os.path.dirname(__file__)
      

      【讨论】:

      • 这将为您提供当前文件所在的目录,该目录可能不是您的当前目录。
      • 对,我误读了原始问题。此外,因此,必须在 inin 文件中调用它才能正常工作。
      【解决方案3】:

      如果您愿意将工作目录作为参数传递给脚本,则可以使用以下方法。

      #!/usr/bin/env python
      import sys
      import os
      
      workingDir = sys.argv[1]
      os.chdir (workingDir)
      
      # Your code here
      

      【讨论】:

      • os.getcwd() 好多了。
      • 为什么? os.getcwd() 获取一个当前工作目录,但我不明白这将如何帮助运行应该在不同子目录中本地运行的代码。
      【解决方案4】:

      听起来很适合 os.walk() 帮助中的示例将是一个很好的起点:

      import os
      from os.path import join, getsize
      for root, dirs, files in os.walk('python/Lib/email'):
          print root, "consumes",
          print sum(getsize(join(root, name)) for name in files),
          print "bytes in", len(files), "non-directory files"
          if 'CVS' in dirs:
              dirs.remove('CVS')  # don't visit CVS directories
      

      【讨论】:

        猜你喜欢
        • 2012-09-06
        • 1970-01-01
        • 2014-10-14
        • 1970-01-01
        • 2023-03-29
        • 2016-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多