Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中列出目录时,如何排除目录(而不是删除目录)_Python - Fatal编程技术网

在python中列出目录时,如何排除目录(而不是删除目录)

在python中列出目录时,如何排除目录(而不是删除目录),python,Python,我正在使用os.walk,我能够成功地列出目录。我使用这些目录作为变量,我不需要几个目录作为它的一部分。如何排除并使所有其他目录向前移动?您需要修改dirs,这将删除操作系统访问的(后续)文件和目录。walk: # exclude = set([...]) for root, dirs, files in os.walk(top, topdown=True): dirs[:] = [d for d in dirs if d not in exclude] 您只需修改即可,即从os.walk()

我正在使用os.walk,我能够成功地列出目录。我使用这些目录作为变量,我不需要几个目录作为它的一部分。如何排除并使所有其他目录向前移动?

您需要修改
dirs
,这将删除操作系统访问的(后续)文件和目录。walk:

# exclude = set([...])
for root, dirs, files in os.walk(top, topdown=True):
dirs[:] = [d for d in dirs if d not in exclude]

您只需修改即可,即从
os.walk()
生成的
子目录列表中删除排除的目录。您可以通过几种方式(我的意思是,就地删除):

首先在代码顶部写下以下内容:

import os

root = "the/path/to/root/dir";
exclude_dir_set = set(['some_dir', 'another_some_dir`])
第一种方法

for current_dir, dirs, files in os.walk(root):
    dirs[:] = list(set(dirs) - exclude_dir_set)
第二种方法:

for current_dir, dirs, files in os.walk(root):
    dirs[:] = [_dir for _dir in dirs if _dir not in exclude_dir_set]
for current_dir, dirs, files in os.walk(root):
    for _dir in dirs:
        try:
            if _dir in exclude_dir_set:
                dirs.remove(_dir)
        except ValueError:
            pass # do nothing
第三种方法:

for current_dir, dirs, files in os.walk(root):
    dirs[:] = [_dir for _dir in dirs if _dir not in exclude_dir_set]
for current_dir, dirs, files in os.walk(root):
    for _dir in dirs:
        try:
            if _dir in exclude_dir_set:
                dirs.remove(_dir)
        except ValueError:
            pass # do nothing

如果您有任何问题,请在评论中提问……

如果您能分享,至少,(a)您目前掌握的代码,(b)您希望“排除”哪些文件夹的标准,以及(c)您解决手头问题的尝试,以及您在所述尝试中遇到的具体问题,这将是一个很大的帮助(为什么您的尝试不符合您的要求)。FileNotFoundError:[Errno 2]没有这样的文件或目录:'/tmp/test/wsx/xxxxx/myfile.txt'。要删除此目录。在下一步(os.walk(“/tmp/xxxx/”))[1]:file=“/tmp/test/{}/xxxx/myfile.txt”。format(dirs)f=open(file,“x”)print('Testing:{}.format(file)),很遗憾,您的评论没有提供更多的清晰性。除此之外,我上面的问题是您提供了要排除某些目录的条件。收到此错误TypeError:'str'对象不支持item assignmentroot=“/tmp/xxxx/”,exclude_dir_set=set(下一个目录中的目录(os.walk(root))[1]:目录[:]=list(set(dirs)-exclude_dir_set)file=“/tmp/test/{}/xxxx/myfile.txt”。format(dirs)f=open(file),“x”)print('Testing:{}.format(file))它在我的电脑中工作得很好。那么,你为什么要使用
next(os.walk(root))
?另外,哪一行给了您错误?我想,您在格式化文件名时遇到了一些问题,请再次检查并共享更新。。。