AMG
AMG

Reputation: 65

In python os.chdir() is not working with relative path

I want to change the working directory in python using os.chdir() from the current project folder to an existing folder in the project folder but it shows a file not found error.

import os

print(os.getcwd())

os.chdir("../NewDirectory/") #Error here

print(os.getcwd())

I expected an output:

C:\Users\John Doe\PycharmProjects\untitled
C:\Users\John Doe\PycharmProjects\untitled\NewDirectory

But I got the result:

C:\Users\John Doe\PycharmProjects\untitled

Traceback (most recent call last):
  File "C:/Users/John Doe/PycharmProjects/untitled/miketest.py", line 5, in <module>
    os.chdir("../NewDirectory/")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '../NewDirectory/'

Upvotes: 2

Views: 6857

Answers (1)

xrisk
xrisk

Reputation: 3898

You say that NewDirectory exists inside untitled which is the current directory.

Then your relative path ../NewDirectory is incorrect because it attempts to find NewDirectory inside the parent of the current directory. That is, it attemps to find NewDirectory inside PycharmProjects; which doesn't exist.

Replacing your call with os.chdir("NewDirectory") should work as expected. "NewDirectory" by itself is a relative path and refers to a directory inside the current one.

If you want to make it more explicit, you can write it as os.chdir("./NewDirectory"), which emphasises the fact that NewDirectory is located inside the current directory (.).

Upvotes: 6

Related Questions