递归搜索模式和列表文件名

时间:2019-06-29 13:37:37

标签: python-3.5

我下面的代码列出了所有文件,无论模式是否匹配。 ss.txt文件不包含模式,但仍获得输出

添加了代码

import os
import re

files = []
pattern = re.compile('my')

for p, d, f in os.walk(r'C:\Users\anaveed\test'):
    for file in f:
        files.append(os.path.join(p, file))

for f in files:
    with open(f, 'r') as x:
        for i in x:
            Var1 = re.search(pattern, i)
        print(f)
        x.close()


C:\Users\anaveed\test\sample.txt
C:\Users\anaveed\test\testfile.txt
C:\Users\anaveed\test\hoax\a.txt
C:\Users\anaveed\test\hoax\ss.txt

1 个答案:

答案 0 :(得分:0)

import os
import re

files = []
pattern = re.compile('my')

for p, d, f in os.walk(r'C:\Users\anaveed\test'):
    for file in f:
        files.append(os.path.join(p, file))

for f in files:
    with open(f, 'r') as x:
        Var1 = False
        for i in x:
            if re.search(pattern, i):
                Var1 = True
        if Var1:
            print(f)
        x.close()

C:\Users\anaveed\test\sample.txt
C:\Users\anaveed\test\testfile.txt
C:\Users\anaveed\test\hoax\a.txt