Search code examples
pythonpython-3.xstringstring-comparison

Check content of text file and add content if it's not there


I am new to python. I am designing a quotes app using python. I am getting the quotes of the day from the brainy quote websites using BeautifulSoup. I would append it to the text file. In here, if the quotes of the day are already added, when I execute the program again, it should skip it. How to make it possible

Here's the code:

from bs4 import BeautifulSoup
import socket
import requests
import subprocess
import datetime
def quotenotify():
    timestamp = datetime.datetime.now().strftime("%b %d")
    res = requests.get('https://www.brainyquote.com/quote_of_the_day')
    soup = BeautifulSoup(res.text, 'lxml')

    image_quote = soup.find('img', {'class': 'p-qotd bqPhotoDefault bqPhotoDefaultFw img-responsive delayedPhotoLoad'})
    quoteday=image_quote['alt']
    text_file = open("quotes.log", "a+")
    text_file.write("%s"%timestamp+"\t"+"%s"% quoteday)
    text_file.write("\n")
    text_file.close()
    return
quotenotify()

output in a file:

Mar 29  Where there is a great love, there are always wishes. - Willa Cather
Mar 29  Where there is great love, there are always wishes. - Willa Cather

Solution

  • Continuing from the comments:

    from bs4 import BeautifulSoup
    import requests
    import datetime
    
    def quotenotify():
        timestamp = datetime.datetime.now().strftime("%b %d")
        res = requests.get('https://www.brainyquote.com/quote_of_the_day')
        soup = BeautifulSoup(res.text, 'lxml')
        image_quote = soup.find('img', {'class': 'p-qotd bqPhotoDefault bqPhotoDefaultFw img-responsive delayedPhotoLoad'})['alt']
        with open("quotes.log", "w+") as f:
            if image_quote not in f.read():
                f.write("%s"%timestamp+"\t"+"%s"% image_quote + "\n")
    
    quotenotify()
    

    EDIT:

    Since using the mode w+ would truncate the file, I'd suggest going with pathlib:

    from bs4 import BeautifulSoup
    import requests
    import datetime
    from pathlib import Path
    
    def quotenotify():
        timestamp = datetime.datetime.now().strftime("%b %d")
        res = requests.get('https://www.brainyquote.com/quote_of_the_day')
        soup = BeautifulSoup(res.text, 'lxml')
        image_quote = timestamp + "\t" + soup.find('img', {'class': 'p-qotd bqPhotoDefault bqPhotoDefaultFw img-responsive delayedPhotoLoad'})['alt']
        with open("quotes3.log", "a+") as f:
            contents = [Path("quotes3.log").read_text()]
            print(contents)
            print(image_quote)
            if image_quote not in contents:
                f.write("%s" % timestamp + "\t" + "%s" % image_quote + "\n")
    
    quotenotify()