剧本目标:
分析日志文件=>;假设主机上的操作成功或失败取决于日志文件中的某些文本=>;提取主机名并将其写入CSV文件
问题:
当我尝试在csv文件中写入数据时,它只输出列表的最后一个成员,并按行显示一个字母
def parselogfiles(directory):
for f in os.listdir(directory):
if f.endswith(".log"):
filepath = os.path.join(directory,f)
if os.stat(filepath).st_mtime > now - 1 * 86400:
with open (filepath, mode="rt", encoding="utf-8") as logfile:
f2 = logfile.read()
if success in f2:
hostname = re.findall(r'\w{1,5}\-\d{1,2}', f2)
accesses = successm+hostname[0]
elif failure in f2:
hostname = re.findall(r'\w{1,5}\-\d{1,2}', f2)
accesses = failmessage+hostname[0]
print(accesses)
return (accesses)
with open(filename, mode='a', newline='') as lg:
writer = csv.writer(lg, dialect='excel')
for l in parselogfiles(logdir):
print (l)
writer.writerow([l])
print("write succeeded")
我想要的是:
成功:HOSTNAME-01
成功:HOSTNAME-02
失败:HOSTNAME-03
我得到的是:
F级
A
我
我
U型
右
电子
地址:
小时
O
S码
T型
不
A
米
电子
-
0个
三
accesses
是一个字符串。通过执行accesses = ...
,在for
循环的每个迭代中重置accesses
,因此return accesses
最终只返回最后一个已处理文件的结果字符串。现在将对该字符串的所有单个字符进行迭代,从而得到所得到的输出
实现所需功能的一种方法是使用列表,并将所有文件的结果字符串放在该列表中。只是对代码做了一些小改动:
相关问题 更多 >
编程相关推荐