Search code examples
pythonpython-3.xreddit

Python script not writing final entry


So I'm making a Reddit bot and it's all working except that the final comment id (used to keep track where the bot already commented) is not writing the final entry.

For example, it wrote 6 of 7 ids to file, but won't write the final one. I'm very new to python so I'm still learning.

subreddit = reddit.subreddit('(thesubredditname)')
keyphrase = '!hayesfact'

for comment in subreddit.stream.comments():
    if keyphrase in comment.body:
        commentid = comment.id
        print(commentid)
        file = open('C:\\Users\\Desktop\\database.txt', "r")

    if commentid in file.read():
        print("already commented")
        file.close
    else:
        file = open('C:\\Users\\Desktop\\database.txt', "a")
        randomInt = randint(1,3)
        print(randomInt)
        file.write("\n" + commentid)
        file.close

        try:
            if randomInt == 1:                    
                comment.reply("Hayes was born on October 4, 1822!")                 
                print('posted and wrote to file')
            if randomInt == 2:
                comment.reply("Hayes signed legislation allowing women to argue before the supreme court!")                 
                print('posted and wrote to file')
            if randomInt == 3:
                comment.reply("Hayes won the electoral vote by only 1!")                 
                print('posted and wrote to file')                
        except:
            print('too frequent')

Solution

  • The main problem would be that you are not calling the file.close() function, just using it as an attribute; add the parethesis to make the function call and that should flush the rest of the file to disk.

    Furthermore, there are a few things in your code that could be improved:

    • what happens if the file is not opened (when if keyphrase in comment.body: is False) ? You will probably get an error because the file won't be opened and the write() call will fail.
    • You should not use a bare except: clause, because that makes debugging hard; specify all errors you are trying to catch.