How to move to one folder back in python

后端 未结 7 2045
眼角桃花
眼角桃花 2021-01-30 09:10

Actually need to go some path and execute some command and below is the code

code:

import os
present_working_directory = \'/home/Desktop         


        
相关标签:
7条回答
  • 2021-01-30 09:27

    Just call

    os.chdir('..')
    

    the same as in any other language :)

    0 讨论(0)
  • 2021-01-30 09:30

    The answers mentioned above are correct. The following is more a It usually happens when your Python script is in a nested directory and you want to go one level up from the current working directory to maybe let's say load a file.

    The idea is to simply reformat the path string and prefix it with a '../'. So an example would be.

    '../current_directory/' + filename
    

    This format is similar to when used in a terminal. Whenever in doubt fire up a terminal and experiment with some commands. The format is reflected in the programming language.

    0 讨论(0)
  • 2021-01-30 09:33

    Here is a very platform independent way to do it.

    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/'
    

    Then you have the path, and you can chdir or whatever with it.

    0 讨论(0)
  • 2021-01-30 09:37

    Just like you would in the shell.

    os.chdir("../nodes")
    
    0 讨论(0)
  • 2021-01-30 09:38

    think about using absolute paths

    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()
    
    0 讨论(0)
  • 2021-01-30 09:47

    Exact answer for your question is os.chdir('../')

    Use case:

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

    To navigate to sub-folder1 from sub-folder2, you need to write like this "../Folder1/sub-folder1/"

    then, put it in os.chdir("../Folder1/sub-folder1/").

    0 讨论(0)
提交回复
热议问题