【问题标题】:Compare old and new values python比较新旧值python
【发布时间】:2023-03-23 19:54:01
【问题描述】:

当我通过if else 比较两个网址时,我总是得到其他(打印test2),如果两个值相同则无关紧要。为什么?代码是:

def derpypost():
    threading.Timer(10.0, derpypost).start()
    print(Fore.CYAN + Style.BRIGHT + "Прошло " + times +
          " минут, начинаю постить картинку в " + vk_group_name)
    print("   Получаю URL картинки")
    real_dp_tags = dp_tags.replace("'", "").replace("'", '')
    for image in Search().query(real_dp_tags).limit(1):
        url = image.image
        source = image.url
        post_tags = image.tags
        sourceurl = image.source_url
    old_url = open('compare.txt', 'r')
    print(old_url.read())
    olded_url = old_url.read()

    if olded_url == url:
        print("test")
    else:
        print('test2')
    old_url.close()
    with open('compare.txt', 'w') as f:
        f.write(url)
        print('WRITTEN!' + url)
        f.close()
derpypost()

compare.txt 中是 - https://example.com/ 在 url 变量中 - https://example.com

【问题讨论】:

  • 将url保存到文件中,读回文件,比较?
  • @PatrickArtner 也是个好主意。但它不会使cpu过载那么多吗?
  • @PatrickArtner 我确实通过文件读取和写入值。当我在做ifelse 时,即使网址相同,我也总是去 esle。 P.S 代码更新

标签: python compare store


【解决方案1】:

这个:

old_url = open('compare.txt', 'r')  # stream at pos 0
print(old_url.read())               # stream at end of file
olded_url = old_url.read()          # nothing to put into variable

不会工作。文件是基于流的,一旦流位于文件末尾,您就可以使用它们。

使用

def writeFile(urlToWrite):
    fn = 'compare.txt'
    with open(fn, 'w') as createFile:
        createFile.write(urlToWrite)
        print("Wrote: " + urlToWrite)  # if you want it to see on console.

def readFile():
    fn = 'compare.txt'
    old_url = ""
    try:
        with open(fn, 'r') as rf:
            old_url = rf.read()
            print("Read: " + old_url)  # if you want it to see on console.
    except FileNotFoundError: # create file if not exists
        writeFile("")
    return old_url

curr_url = "tata"
old = readFile()
if old != curr_url:
    writeFile(curr_url)

输出(第一次使用 tata,然后为 curr_url 纹身):

Read: tata
Wrote: tattoo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多