比较旧值和新值python

时间:2018-02-04 22:08:34

标签: python compare store

当我通过if else比较两个网址时,我总是得到其他信息(Prints 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

1 个答案:

答案 0 :(得分:0)

此:

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