亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查文本文件的內容,如果不存在則添加內容

檢查文本文件的內容,如果不存在則添加內容

HUWWW 2021-12-21 17:34:50
我是python的新手。我正在使用 python 設計一個報價應用程序。我使用 BeautifulSoup 從聰明的報價網站獲取當天的報價。我會將它附加到文本文件中。在這里,如果當天的報價已經添加,當我再次執行程序時,它應該跳過它。如何使它成為可能這是代碼:from bs4 import BeautifulSoupimport socketimport requestsimport subprocessimport datetimedef 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()    returnquotenotify()在文件中輸出:Mar 29  Where there is a great love, there are always wishes. - Willa CatherMar 29  Where there is great love, there are always wishes. - Willa Cather
查看完整描述

2 回答

?
catspeake

TA貢獻1111條經驗 獲得超0個贊

繼續評論:


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

編輯:


由于使用該模式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()


查看完整回答
反對 回復 2021-12-21
?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

您應該首先以讀取模式打開文件并將內容加載到變量中。


您可以在下面的示例中看到,我將內容加載到變量中,然后僅當變量不在文本文件中時才附加到文件中。


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


查看完整回答
反對 回復 2021-12-21
  • 2 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號