简体   繁体   English

os.walk缺少某些子目录

[英]os.walk missing out certain subdirectories

for dirname, dirnames, filenames in os.walk("C:\\",followlinks=True,topdown=True):

    for subdirname in dirnames:    
        os.chdir(os.path.join(subdirname, dirname))

        if os.getcwd()!="C:\Windows\winsxs":
            print(os.getcwd())

As you can see, this code is supposed to search the entire C drive for all subdirectories and change Python's working directory and display the result. 如您所见,该代码应该在整个C驱动器中搜索所有子目录,并更改Python的工作目录并显示结果。 I can't help but notice for whatever reason, os.walk has been missing out quite a few subdirectories. 我不禁注意到,无论出于什么原因,os.walk都丢失了很多子目录。 It seems to find a big directory tree and then only scan about half of it before moving on (Or at least that's the case with the directories I've checked such as desktop) 似乎找到了一个大目录树,然后在继续之前仅扫描了一半左右(或者至少我已经检查过的目录就是这种情况,例如台式机)

I've scoured the net, but I can't seem to find anyone else who has had this problem, some help would be really appreciated (I am a novice coder). 我已经搜寻过网络,但似乎找不到其他遇到此问题的人,我们将不胜感激(我是新手编码人员)。

EDIT: The solution worked, but now I get a permission error when I run the code. 编辑:解决方案有效,但是现在我在运行代码时收到权限错误。

Your join is wrong. 您的加入是错误的。 It must be: 一定是:

os.chdir(os.path.join(dirname, subdirname))

That's why you never enter the highest directory levels. 这就是为什么您永远不会输入最高目录级别的原因。

As documentation (here: https://docs.python.org/2/library/os.html#os.walk ) states, to get a full path to a file or directory in dirpath, do os.path.join(dirpath, name). 如文档(此处: https ://docs.python.org/2/library/os.html#os.walk)所述,要获取目录路径中文件或目录的完整路径,请执行os.path.join(dirpath , 名称)。

Your join should be: 您的加入应为:

os.chdir(os.path.join(dirname, subdirname))

TO YOUR EDIT: If you want to search all directories, you may find some that you have no permission to enter or read as a normal user. 编辑:如果要搜索所有目录,可能会发现一些您无权以普通用户身份输入或阅读的目录。 If you want to do it, you'd probably have to use your administrator account. 如果要执行此操作,则可能必须使用管理员帐户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM