用Python从第二个文件的列表中搜索一个文件

2024-04-23 15:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次在这里发帖,我只是在学习python,所以请耐心听我说。 我已经在这里和其他地方进行了很好的研究,试图找到一个答案,但唉,网络似乎失去了!你知道吗

我有一个每天生成的日志文件,它可以包含许多语法不同的错误。其中一些是重要的,其他是微不足道的,但由于事实上,他们都包含文本“错误”,我不能只搜索一个字。你知道吗

我有一个错误的文本列表,这些错误以前在一个文件中出现过,我想将日志文件与之进行比较,以便在出现任何错误时发出警告。你知道吗

我已经设法让它为一个错误工作,但我不能让它为列表工作。你知道吗

工作代码如下:

    log_file = open ('a file location' , 'r')
    read_file = file.read ()
    search = read_file.find ('Error type 1 happened at x')
    if search != -1:
        print 'Error found in  log at point ' + str((search)) + '!!!'
    else :
        print "All is good!!!  :-D "

对于列表,我尝试了以下方法:

    load_log_file = open ('a file location' , 'r')
    read_log_file = load_log_file.read ()

    def txt_search (read_log_file):
        errors = open ('another file location' , 'r')
    for error in errors.readlines() :
            if error.strip ('\r\n') in read_log_file:
                return 'Error found in log !!!'
            else :
                return "All is good!!!  :-D "

    print txt_search (read_log_file)

我得到一个结果时,这是运行,但它总是回来与“一切都很好”。 我可能错过了一些非常明显的东西,但任何帮助都会得到很大的回报。你知道吗

非常感谢


Tags: 文件in文本log列表readsearchif
1条回答
网友
1楼 · 发布于 2024-04-23 15:23:46

你过早地回来了。你知道吗

load_log_file = open ('a file location' , 'r')
read_log_file = load_log_file.read ()

def txt_search (read_log_file):
    errors = open ('another file location' , 'r')
    for error in errors.readlines() :
        if error.strip ('\r\n') in read_log_file:
            return 'Error found in log !!!'

    return "All is good!!!  :-D "

print txt_search (read_log_file)

在原始代码中发生的是,它查找第一个错误,但没有找到,然后返回“All is good”。始终记住return语句结束函数。你知道吗

相关问题 更多 >