简体   繁体   English

如何阅读包含特定字符串的最后修改文件?

[英]How do I read the last modified file that contains a certain string?

I want to find the last modified file that contains a string using python. 我想使用python查找包含字符串的最后修改文件。 I have many files in my directory so comparing dates is not appealing. 我的目录中有很多文件,因此比较日期并不吸引人。 I am looking for a way to search the file by modified data until I hit a file containing the string I want. 我正在寻找一种通过修改后的数据搜索文件的方法,直到找到包含所需字符串的文件为止。 Or if there is a better way to do this that would be great. 或者,如果有更好的方法可以做到这一点,那就太好了。

To search for the last modified file in the current directory that contains the string search_string , you can use this code: 要在当前目录中搜索包含字符串search_string的最后修改的文件,可以使用以下代码:

files = os.listdir(".")
files.sort(key=os.path.getmtime, reverse=True)
for name in files:
    with open(name) as f:
        if search_string in f.read():
            print name
            break

This will first list all the files, sort them by modification time, newest first, and then iterates over the list of files to see if they contain search_string . 这将首先列出所有文件,并按修改时间对它们进行排序(最新的),然后遍历文件列表以查看它们是否包含search_string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM