vaindil
vaindil

Reputation: 7844

Traversing directories and performing command prompt commands in each with Python

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\"')

Upvotes: 1

Views: 749

Answers (1)

Dan Lenski
Dan Lenski

Reputation: 79742

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\"')

Upvotes: 4

Related Questions