【问题标题】:How to move to one folder back in python如何在python中移回一个文件夹
【发布时间】:2012-08-30 02:18:57
【问题描述】:

实际上需要走一些路径并执行一些命令,下面是代码

代码

import os
present_working_directory = '/home/Desktop/folder' 

目前我在folder

if some_condition == true :
    change_path = "nodes/hellofolder"
    os.chdir(change_path)
    print os.getcwd()
if another_condition  == true:
    change_another_path = "nodes" 
    os.chdir(change_another_path) 
    print os.getcwd()

**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory

实际上这里发生的事情是当我第一次使用os.chdir()时,目录已更改为

'/home/Desktop/folder/nodes/hellofolder',

但是对于第二个,我需要通过移回一个文件夹来运行文件

'/home/Desktop/folder/nodes'

谁能告诉我如何在python中将一个文件夹移回

【问题讨论】:

  • 尽可能避免使用os.chdirsubprocess 模块的函数将工作目录作为参数。 (另外,true 应该是 True== True 从来没有必要。)
  • @Kour ipm,正如 larsmans 所说,使用子进程做你需要做的事情,它有关键字 cwd。所以调用你需要的东西: subprocess.call("yourCommand", shell=True, cwd="path/to/directory")

标签: python operating-system


【解决方案1】:

就像在 shell 中一样。

os.chdir("../nodes")

【讨论】:

    【解决方案2】:

    这是一种非常独立于平台的方法。

    In [1]: os.getcwd()
    Out[1]: '/Users/user/Dropbox/temp'
    
    In [2]: os.path.normpath(os.getcwd() + os.sep + os.pardir)
    Out[2]: '/Users/user/Dropbox/'
    

    然后你就有了路径,你可以 chdir 或其他任何东西。

    【讨论】:

    • ''/Users/user/ 怎么样?
    • 感谢您添加此内容。这应该是实际答案
    【解决方案3】:

    只要打电话

    os.chdir('..')
    

    与任何其他语言相同:)

    【讨论】:

      【解决方案4】:

      您的问题的确切答案是os.chdir('../')

      用例:

      Folder1:
          sub-folder1:(you want to navigate here)
      Folder2:
          sub-folde2:(you are here)
      

      要从sub-folder2 导航到sub-folder1,你需要这样写 "../Folder1/sub-folder1/"

      然后,将其放入os.chdir("../Folder1/sub-folder1/")

      【讨论】:

        【解决方案5】:

        考虑使用绝对路径

        import os
        pwd = '/home/Desktop/folder'
        
        if some_condition == true :
            path = os.path.join(pwd, "nodes/hellofolder")
            os.chdir(path)
            print os.getcwd()
        if another_condition  == true:
            path = os.path.join(pwd, "nodes")
            os.chdir(path) 
            print os.getcwd()
        

        【讨论】:

          【解决方案6】:

          这个命令解决了我的问题 第一个 import os 和后添加 os.path.normpath(os.path.abspath(__file__) + os.sep + os.pardir)

          【讨论】:

            【解决方案7】:

            上面提到的答案是正确的。以下是更多 它通常发生在您的 Python 脚本位于嵌套目录中并且您想从当前工作目录上一级以加载文件时。

            这个想法是简单地重新格式化路径字符串并在其前面加上'../'。所以一个例子就是。

            '../current_directory/' + filename
            

            此格式类似于在终端中使用时的格式。如有疑问,请启动终端并尝试一些命令。格式反映在编程语言中。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2010-09-08
              • 2013-12-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多