0

I am trying to create my first python program that deletes any empty directories within d:\source. It appears I can't even enter the directory with my current skills:

import os
os.getcwd()
os.chdir("D:\\SOURCE")
os.getcwd()

All I get is...

D:\CODING\venv\Scripts\python.exe D:/CODING/tester.py

Process finished with exit code 0

It seems it has not changed the working dir, how do I verify that? Why won't it display the results/errors for the os.chdir("D:\\SOURCE") or the second os.getcwd() command at all?

num3ri
  • 822
  • 16
  • 20
Bricktop
  • 533
  • 3
  • 22

3 Answers3

4

Chances are your program indeed changes the directory. But you cannot see this:

  • A mere os.getcwd() won't do anything visible: it retrieves the current working directory and discards it. Instead, you should do print(os.getcwd())
  • Changing the current working directory only affects the current process (i. e., the Python program), but not its parent (the command prompt). So your command prompt keeps its cwd and doesn't inherit the one from the called program.
glglgl
  • 89,107
  • 13
  • 149
  • 217
  • What would `os.chdir("D:\\SOURCE")` look like with added security? Like if directory change fails then do not continue. – Bricktop Sep 03 '19 at 19:23
  • 1
    @Bricktop Let's try it: `>>> os.chdir("doesn't exist")` leads to an exception `OSError: [Errno 2] No such file or directory: "doesn't exist"`. So you surround it with `try:` and `except OSError, e:` and check the properties of `e`. – glglgl Sep 03 '19 at 20:44
  • I understand all except the `e:` and `e` properties part but I got the conditions to work. Is it possible to just launch a directory chooser window for a missing directory? – Bricktop Sep 04 '19 at 06:03
  • 1
    @Bricktop Well, essentially that's basic [exception handling](https://wiki.python.org/moin/HandlingExceptions) which you'd have to look up. Of course it is possible to launch a chooser dialog: see [here](https://stackoverflow.com/questions/3579568/choosing-a-file-in-python-with-simple-dialog). – glglgl Sep 04 '19 at 07:42
1

You need to print the result.

import os
print(os.getcwd())
os.chdir("D:\\SOURCE")
print(os.getcwd())
ErikXIII
  • 557
  • 2
  • 12
1

os.chdir() doesn't return any value. It will just change the directory. As suggested in other answers you can print/output the current directory using

os.chdir("D:\\SOURCE") 
print(os.getcwd())
Janki Vyas
  • 101
  • 4