函数以字母而不是字符串的形式呈现元素

2024-10-01 02:29:25 发布

您现在位置: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")

我想要的是:

成功:HOSTNAME-01

成功:HOSTNAME-02

失败:HOSTNAME-03

我得到的是:

F级

A

U型

电子

地址:

小时

O

S码

T型

A

电子

-

0个


Tags: 文件csvingtifosdirectoryhostname
1条回答
网友
1楼 · 发布于 2024-10-01 02:29:25

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")

相关问题 更多 >