如何在Python中返回上一级文件夹

48

实际上需要进入某个路径并执行一些命令,以下是代码:

代码

import os
present_working_directory = '/home/Desktop/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中向上移动一个文件夹吗?


2
如果可以的话,避免使用 os.chdirsubprocess 模块的函数将工作目录作为参数。此外,true 应该是 True,而 == True 从未必要。 - Fred Foo
1
@Kour ipm,正如larsmans所说,使用subprocess做你需要做的事情,它有关键字cwd。因此,使用以下命令调用你需要的内容:subprocess.call("yourCommand", shell=True, cwd="path/to/directory") - oz123
8个回答

62

就像您在 shell 中一样。

os.chdir("../nodes")

53

这里有一种非常平台无关的方法来完成它。

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/”怎么获取? - Naravut Suvannang
感谢您添加这个。这应该是实际答案。 - Rohan Arora

34

只需要调用

os.chdir('..')

和其他任何语言一样 :)


2
尝试使用这个,但它不起作用。一旦我尝试更改使用这个,我的路径就变成了“无”。 - ThisQRequiresASpecialist

6

您的问题的确切答案是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/")中。


2

考虑使用绝对路径

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()

2
上述答案是正确的。以下更多地涉及编程问题。当您的Python脚本位于嵌套目录中且希望从当前工作目录向上一级,例如加载文件时,通常会出现此问题。
解决方法是简单地重新格式化路径字符串,并在前面加上“../”。例如:
'../current_directory/' + filename

这种格式类似于在终端中使用时的格式。每当有疑问时,打开终端并尝试一些命令。这种格式体现在编程语言中。


1

使用以下命令解决了我的问题:首先导入os,然后添加os.path.normpath(os.path.abspath(__file__) + os.sep + os.pardir)


0

在你的脚本中定义这个函数,每当你想要返回到上一级文件夹时调用它:

import os

def dirback():
    m = os.getcwd()
    n = m.rfind("\\")
    d = m[0: n+1]
    os.chdir(d)
    return None

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接