首页 > 解决方案 > 匹配模式并填充 csv 文件

问题描述

试图打开一个文件并在每一行中搜索一个字符串。如果字符串匹配,我想将“通过”或“失败”写入 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()

标签: python-3.x

解决方案


它应该是 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()

推荐阅读