Edward A.
Edward A.

Reputation: 1

python os.chdir() cant be used multiple times?

when I first use the os.chdir() it works then when I try using it again it does not and give me an error. the following files have been created. ed and 123

import os 
os.mkdir('ed')
os.mkdir('123')

now i want to change between the two.

import os
os.chdir('ed')

os.chdir('123')

Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
os.chdir('123')
FileNotFoundError: [WinError 2] The system cannot find the file specified: '123'

why wont it let me change between the two files ?

Upvotes: 0

Views: 1697

Answers (2)

DeepSpace
DeepSpace

Reputation: 81654

Think of calling os.chdir(some_path) the same as doing cd some_path from the terminal. It considers the provided path to be relative unless being explicitly given an absolute path (starting with drive letter on Windows or / on Linux).

for os.chdir('ed') ; os.chdir('123') to work 123 dir must be a subdir of ed. In your case it is not, so you will either need to:

  1. provide absolute path
  2. go back one level before calling os.chdir('123'):

    os.chdir('..')
    os.chdir('123')
    

    or even

    os.chdir('..{}123'.format(os.path.sep))
    

    Note the use of os.path.sep in order to avoid using OS specific path separator.

Upvotes: 2

user4851164
user4851164

Reputation: 41

After creating ed and 123 folder, these two folders are at same level.

os.chdir('ed') 

Above line will point you into ed folder.

os.chdir('../123') 

You need to use .. to navigate to parent folder and then navigate to 123 folder.

Upvotes: 2

Related Questions