首页 > 解决方案 > 函数逐字母呈现元素而不是字符串

问题描述

脚本的目标:

解析日志文件 => 根据日志文件中的某些文本说主机上的操作是成功还是失败 => 提取主机名并将它们写入 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

标签: pythonpython-3.xfunction

解决方案


accesses是一个字符串。您可以通过执行accesses在循环的每次迭代中重置,因此最后将只返回最后处理的文件的结果字符串。现在,foraccesses = ...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")

推荐阅读