我是Stackoverflow的新手。在编写以下代码时,我从该论坛中获得了很多帮助。下面的代码搜索系统驱动器上的所有目录/子目录,但在查找“ 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')
在Windows中,每个进程可以在每个驱动器上分别设置一个当前工作目录。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):
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句