我对堆积如山很陌生。在编写下面的代码时,我从这个论坛获得了很多帮助。下面的代码搜索系统驱动器上的所有目录/子目录,但是在查看'D‘驱动器时,它只查找那些目录和子目录,这些目录和子目录都是我运行这个程序的文件夹。
我的意思是,如果我运行这个程序从D:\Dir1\Dir2\Dir3\myCode.py,它将搜索目录和子目录后的D:\Dir1\Dir2\Dir3\,而不是整个'D‘驱动器。它很好地运行在其他驱动器,同时从相同的位置运行。这是我的密码:
import os, string
total=0
for driveLetter in string.ascii_uppercase:
try:
if os.path.exists(driveLetter+':'):
for root, dirs, docs in os.walk(top=driveLetter+':', topdown=True):
for name in docs:
try:
if (name.endswith(".docx")) or (name.endswith(".doc")):
print(os.path.join(root, name))
total+=1
except:
continue
except:
continue
print ('You have a total of ' + str(total) + ' word documents in your System')发布于 2016-09-17 05:09:03
在Windows separately中。D:意味着驱动器D上的当前工作目录在这里会发生行为,因为在所有其他驱动器上,当前工作目录被设置为根目录,而在D:上,则是D:\Dir1\Dir2\Dir3\,因为工作目录被更改为脚本的位置。要明确引用D:的根目录,需要使用D:\。因此
drive_root = drive_letter + ':\\' # double \\ because this is a Python string literal
if os.path.exists(drive_root):
for root, dirs, docs in os.walk(drive_root, topdown=True): https://stackoverflow.com/questions/39542635
复制相似问题