python-3.x - 匹配模式并填充 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()
解决方案
它应该是
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()
推荐阅读
- linux - 如何阻止别名在启动时被评估
- sql - 如何在 PostgreSQL 中创建条件外键?
- java - 如何解释方法参数中的表达式?
- python - 什么是在 pd.dataframe 中查找一组连续常量值的干净 Python 方法?
- input - 如何控制输入值是反应形式的整数
- angular - 在 Angular 6 / Ionic 4 功能模块中提供服务时的循环依赖
- excel - 从大型数据集中提取最小/最大/平均数据的宏
- sql - 在浮点值上乘以 startdate = 00:00:00 和 enddate HH:mm:ss 之间的小时差
- google-sheets - 允许插入新数据行但不更改公式
- c# - 取消带参数的任务