使用Python遍历目录并在每个目录中执行命令提示符命令



在Windows 7 Pro中,我需要遍历给定位置(在本例中为Z:)的目录,并使用Python在每个目录中执行命令提示符命令。这看起来应该是直截了当的os.walk(),但到目前为止,我所尝试的都没有奏效——我所得到的最接近的是让命令从我的桌面无限循环(该脚本如下)。我需要做些什么来完成这个任务?

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

当您运行os.system('cd WHEREVER')时,您正在创建一个新的命令shell,该shell对当前目录有自己的想法。

当shell退出时,父进程不会保留子进程的当前目录,因此后续的os.system()调用不会看到当前目录的任何更改。

正确的方法是更改父进程(脚本)中的当前目录,该目录将由子进程继承:
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"')

最新更新