简单的python搜索日志文件脚本是按顺序排序的,但在30个文件之后就按顺序完成了

2024-04-25 16:52:56 发布

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

我有一个简单的python脚本,它在目录中的文件中搜索搜索项及其排序方式操作系统路径获取时间(获取创建时间)。当我直接打印文件名列表时,它是按照从最新到最旧的顺序正确打印的。但当我试图执行这段代码时,过去30个左右的文件并不是以最新的开始。如果我只搜索前30个左右的文件,它的工作如预期。有人能告诉我这是python的东西还是我的代码有问题吗?我做错什么了?参见下面的代码。你知道吗

import os

os.chdir('/home/user/logs/')
mystr = input('search string: ')


files = sorted(os.listdir('.'),key=os.path.getctime, reverse=True)

def search(start, stop):
    for file in files[start:stop]:
        print(file)
        with open(file, 'r') as infile:
            for line in infile:
                if mystr in line:
                    print(line)


search(0,31) #works
search(0,400) #searches out of order or starts at weird order number.

Tags: 文件代码inforsearchosline时间