脚本目标:
解析日志文件=>根据日志文件中的某些文本,说在主机上的操作成功或失败=>提取主机名并将其写入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
我
L
U
R
E
:
H
O
S
T
N
A
M
E
-
0
3
答案 0 :(得分:1)
accesses
是一个字符串。通过执行accesses
,可以在for
循环的每个迭代中重置accesses = ...
,因此最后,return accesses
将仅返回最后处理文件的结果字符串。现在,
for l in parselogfiles(logdir):
print (l)
writer.writerow([l])
将遍历该字符串的所有单个字符,从而获得所需的输出。
一种实现所需目标的方法是改为使用列表,然后将所有文件的结果字符串放入该列表中。这只是对代码的一些小改动:
def parselogfiles(directory):
accesses = [] # is now an empty list
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.append(successm+hostname[0]) # saves the result to the list
elif failure in f2:
hostname = re.findall(r'\w{1,5}\-\d{1,2}', f2)
accesses.append(failmessage+hostname[0])
print(accesses) # will print the list once after every file
return (accesses) # returns the list after all files have been processed
with open(filename, mode='a', newline='') as lg:
writer = csv.writer(lg, dialect='excel')
for l in parselogfiles(logdir): # now will print elements of the list instead of characters in the string
print (l + '\n')
writer.writerow([l])
print("write succeeded")