简体   繁体   中英

How to find a file with specific content?

I have file with this content:

Sent
Trash
Drafts
Junk

and I want to find and delete it with Python.

I know the loop to search files and open the file and I know how regular expressions work, but regex reads files line by line and I can't just search with the key words because there are many files that contain these words (like 'Send' ) and I want the exact content. What can I do?

I thought something like this:

with open(fullsourcefilename) as openfile:
   if openfile.read() == "Sent\nTrash\nDrafts\nJunk":

but it don't work.

Try a multiline regex:

import re

with open(fullsourcefilename) as openfile:
   if re.search(r'Sent\nTrash\nDrafts\nJunk\n', openfile.read(), re.MULTILINE):

This is not the most optimal check if you have large files, but works if all you need is a quick and dirty solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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