Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.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 使用glob或os.walk()忽略特定目录中的文件_Python - Fatal编程技术网

Python 使用glob或os.walk()忽略特定目录中的文件

Python 使用glob或os.walk()忽略特定目录中的文件,python,Python,我想排除目录'dir3_txt',以便只能从其他目录捕获文件('.txt')。我试图排除下面这样的目录,但无法找到如何使用下面的方法获取所有以.txt作为ext的文件,而不是在dir3\u txt中使用它的文件: for root, dirs, files in os.walk('.'): print (root) dirs[:] = [d for d in dirs if not d.startswith('dir3')] for file in files:

我想排除目录'dir3_txt',以便只能从其他目录捕获
文件('.txt')
。我试图排除下面这样的目录,但无法找到如何使用下面的方法获取所有以.txt作为ext的文件,而不是在
dir3\u txt
中使用它的文件:

for root, dirs, files in os.walk('.'):
   print (root)
   dirs[:] = [d for d in dirs if not d.startswith('dir3')]
   for file in files:
        print (os.path.join(root, file))
我正在考虑glob(从堆栈本身获得),但不确定如何调整glob来使用它

for file in os.walk('.'):
   for txt in glob(os.path.join(files[0], '*.txt')):
       print(txt)

我通过了,但提供的解决方案对我没有帮助,而且它只告诉我跳过目录,这也没有帮助,因为我需要从其他目录获取文件,如果我们只使用glob就更好了?

一个简单的解决方案就是将字符串与操作系统返回的目录路径和文件进行比较。walk:

for root, dirs, files in os.walk('.'):
   if "/dir3_txt/" not in root:
       for file in files:
            if file.endswith(".txt"):
                print (os.path.join(root, file))
我没有任何系统与我现在测试这个,所以如果有任何问题,请评论

编辑:


现在它只检测“.txt”文件。

你的目录树是什么样子的?@georgexsh在当前的工作目录中,比如说
/home/users/steve/Desktop
,我有多个单独的文件夹,如
dir1、dir2、dir3\u-txt、dir4
,在
dir3\u-txt
中也可以有txt文件的子文件夹。脚本放在
/home/users/steve/Desktop
中,请阅读-总结是,这不是向志愿者讲话的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。但是如何在此处包含
glob
,以从其他目录及其子目录获取所有文件
.txt
。我试图在glob(os.path.join(files[0],'*.txt'))中为txt设置
在第二个for循环下,但它无法列出。txt对文件进行字符串比较(请参见我的编辑),您可以使用
fnmatch
进行文件名匹配。
for root, dirs, files in os.walk('.'):
   print (root)
   dirs[:]= [d for d in dirs if d[:4]!='dir3']
   for file in files:
      if file[-4:]=='.txt':
        print (os.path.join(root, file))