Home > Net >  Changing Current Working Directory will not work
Changing Current Working Directory will not work

Time:11-12

First time Python learner here, trying to change the current working directory of my project. I can retrieve the default working directory, however attempting to change it proves harder. I've tried all combinations but I keep getting 'None' as a response to my Print command of the new directory.

No idea what is going on

The code I tried was:

print ('----New Run----')
import os
cwd = os.getcwd()
print ('Current Working Directory is: ', cwd)
cwd = os.chdir(r'C:\Users\danie\Documents\Programming\Python\Projects\test')
print ('New Working Directory is: ', cwd)
print ('----End Run----')

Responds with the following in Terminal:

----New Run---- Current Working Directory is: C:\Users\danie\Documents\Programming New Working Directory is: None ----End Run----

I've also tried using

cwd = os.chdir('.\\Python\\Projects\\test')

To which yielded the same result.

CodePudding user response:

That's not how you get the changed directory.

Try this:

print ('----New Run----')
import os
cwd = os.getcwd()
print ('Current Working Directory is: ', cwd)
os.chdir(r'C:\Users\danie\Documents\Programming\Python\Projects\test')
print ('New Working Directory is: ', os.getcwd())
print ('----End Run----')

The chdir() function only changes the directory. It doesn't return the current working directory. You need to use getcwd() seperately to get the new current working directory.

  • Related