python - 函数逐字母呈现元素而不是字符串
问题描述
脚本的目标:
解析日志文件 => 根据日志文件中的某些文本说主机上的操作是成功还是失败 => 提取主机名并将它们写入 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")
我想要得到的是:
成功:主机名-01
成功:主机名-02
失败:主机名-03
我得到的是:
F
一种
一世
大号
ü
R
乙
:
H
○
小号
吨
ñ
一种
米
乙
-
0
3
解决方案
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")
推荐阅读
- java - Using Bazel java_proto_library on Alpine
- python - Remove rows from a panda dataframe with unsorted index
- node.js - S3.upload not working in production environment but working in localhost NodeJS
- python - Batch File (.bat) Equivalent of Shell Script (.sh) "&!"
- python - What causes an Altair Chart to be displayed when it is the last statement in a JupyterLab cell?
- javascript - Rails 6 javascript file isn't grabbing html element properly
- css - CSS绝对按钮具有通过按钮“推送”的输入字段
- react-native - React Navigation v4 remove Bottom navigator
- reactjs - 有没有办法在反应中将道具传递给包含的组件?
- r - Having issues installing gam package in RStudio ver. 3.6.2