1

In Windows 7 Pro, I need to traverse directories at a given location (in this case Z:\) and perform command prompt commands in each using Python. This seems like it should be straightforward with os.walk(), but nothing I've tried so far has worked--the closest I've gotten is to have the commands infinitely loop from my desktop (that script is below). What do I need to do to accomplish this task?

import os

for root, dirs, files in os.walk("Z:/"):
    for dir in dirs:
        os.system('cd Z:\\' + dir)
        os.system('git init')
        os.system('git add .')
        os.system('git commit -m \"Initial\"')
vaindil
  • 7,536
  • 21
  • 68
  • 127
  • 2
    First off, doing os.system('cd Z:\\' + dir) won't actually change your working directory (it will change it for that command, and then when that command finishes, you'll be back at your starting point. You can try os.chdir(dir) but I'm not entirely sure how chdir and stupid archaic drive letters interact – Foon Jun 18 '14 at 19:10

1 Answers1

4

When you run os.system('cd WHEREVER') you are creating a new command shell which has its own idea of the current directory.

When that shell exits, the parent process does not retain the current directory of the child process, so that the subsequent os.system() calls don't see any change in their current directory.

The right way to do this is to change the current directory in the parent process (your script) which will be inherited by the child process:

import os

for root, dirs, files in os.walk("Z:/"):
    for dir in dirs:
        os.chdir('Z:\\' + dir)
        os.system('git init')
        os.system('git add .')
        os.system('git commit -m \"Initial\"')
Dan Lenski
  • 76,929
  • 13
  • 76
  • 124
  • 1
    Does this require some `os.path.join` magic? Like `path = os.path.join('Z:\\', dir)` and `os.chdir(path)` to make sure it is readable by Windows? And I would add that he could include some tests with `os.path.exists(path)` this way. I am commenting to clarify for myself; file manipulations in Windows always get me. – Engineero Jun 18 '14 at 19:17
  • 1
    @Engineero, agreed that it would be good cross-platform practice to use `os.path.*` rather than just glom strings together, but I'm trying to make the minimal changes to the OP's code without getting bogged down in other issues. The path in question must exist because `os.walk` told us that it did, except in case it got `rmdir`'d while this script is running ;-) – Dan Lenski Jun 18 '14 at 19:20
  • I see, thanks for the clarification and sorry to muddy the waters. – Engineero Jun 18 '14 at 19:21
  • @Engineero, there are definitely other issues with this code. I recommended [never using `os.system` in another thread](http://stackoverflow.com/questions/24294179/python-reading-whitespace-separated-file-lines-as-separate-lines/24294225#comment37542761_24294225) started by @Vaindil. – Dan Lenski Jun 19 '14 at 00:03