Changing Current Working Directory will not work
Question:
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:UsersdanieDocumentsProgrammingPythonProjectstest')
print ('New Working Directory is: ', cwd)
print ('----End Run----')
Responds with the following in Terminal:
—-New Run—-
Current Working Directory is: C:UsersdanieDocumentsProgramming
New Working Directory is: None
—-End Run—-
I’ve also tried using
cwd = os.chdir('.\Python\Projects\test')
To which yielded the same result.
Answers:
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:UsersdanieDocumentsProgrammingPythonProjectstest')
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.
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:UsersdanieDocumentsProgrammingPythonProjectstest')
print ('New Working Directory is: ', cwd)
print ('----End Run----')
Responds with the following in Terminal:
—-New Run—-
Current Working Directory is: C:UsersdanieDocumentsProgramming
New Working Directory is: None
—-End Run—-
I’ve also tried using
cwd = os.chdir('.\Python\Projects\test')
To which yielded the same result.
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:UsersdanieDocumentsProgrammingPythonProjectstest')
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.