匹配模式并填充csv文件

时间:2018-07-20 00:16:12

标签: python-3.x

尝试打开文件并在每一行中搜索字符串。如果字符串匹配,我要向CSV文件写入“通过”或“失败”。下面的代码不起作用。请协助。

import re
path = 'C:/mypath'
fh = open("C:/report.csv", "w+")
print('Device Name', 'Compliance Check 1', sep=",", file=fh)

for filename in os.listdir(path):
    with open(os.path.join(path,filename), "r") as infile:
        for line in infile:
            if re.match('some string'):
                check1 = 'pass'
            fh.write("{},{}\n".format(filename, check1))
fh.close()

1 个答案:

答案 0 :(得分:0)

应该是 result = re.match(pattern, string)

因此,在这种情况下,re.match('some string', line)

如果您不使用正则表达式,则可以执行line.startswith('some string')

此外,如果没有匹配项,则不会为check1设置值,也不要为每行重置该值。

我相信您只想为每个文件写一次“通过”或“失败”,这样我就不会缩进。

import re
path = 'C:/mypath'
fh = open("C:/report.csv", "w+")
print('Device Name', 'Compliance Check 1', sep=",", file=fh)

for filename in os.listdir(path):
    with open(os.path.join(path,filename), "r") as infile:
        check1 = 'fail'
        for line in infile:
            if re.match('some string', line):
                check1 = 'pass'
        fh.write("{},{}\n".format(filename, check1))
fh.close()