Проверьте содержимое текстового файла и добавьте содержимое, если его там нет - PullRequest
2 голосов
/ 29 марта 2019

Я новичок в питоне.Я разрабатываю приложение для цитат, используя pythonЯ получаю цитаты дня с мозговитых цитат, использующих BeautifulSoup.Я бы добавил его в текстовый файл.Здесь, если цитаты дня уже добавлены, при повторном запуске программы она должна быть пропущена.Как сделать возможным

Вот код:

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()

вывод в файл:

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

Ответы [ 2 ]

1 голос
/ 29 марта 2019

Продолжая из комментариев:

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

Поскольку использование режима w+ приведет к усечению файла, я бы предложил использовать 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()
0 голосов
/ 29 марта 2019

Как уже упоминалось @DirtyBit, вы должны сначала открыть файл в режиме чтения и загрузить содержимое в переменную.

В моем примере ниже вы можете видеть, что я загружаю содержимое в переменную, затем добавляюв файл, только если переменная не находится внутри текстового файла.

text_file = open('test-file.txt', 'r+')
read_the_file = text_file.read()
text_file.close()

text_file = open('test-file.txt', 'a+')
new_string = 'Smack Alpha learns python'

if new_string not in read_the_file:
    text_file.write(new_string + '\n')
text_file.close()
...