首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python os.walk()方法

Python os.walk()方法
EN

Stack Overflow用户
提问于 2016-09-17 03:42:45
回答 1查看 350关注 0票数 1

我对堆积如山很陌生。在编写下面的代码时,我从这个论坛获得了很多帮助。下面的代码搜索系统驱动器上的所有目录/子目录,但是在查看'D‘驱动器时,它只查找那些目录和子目录,这些目录和子目录都是我运行这个程序的文件夹。

我的意思是,如果我运行这个程序从D:\Dir1\Dir2\Dir3\myCode.py,它将搜索目录和子目录后的D:\Dir1\Dir2\Dir3\,而不是整个'D‘驱动器。它很好地运行在其他驱动器,同时从相同的位置运行。这是我的密码:

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-17 05:09:03

在Windows separately中。D:意味着驱动器D上的当前工作目录在这里会发生行为,因为在所有其他驱动器上,当前工作目录被设置为根目录,而在D:上,则是D:\Dir1\Dir2\Dir3\,因为工作目录被更改为脚本的位置。要明确引用D:的根目录,需要使用D:\。因此

代码语言:javascript
复制
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):            
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39542635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档