Python 脚本未写入最终条目
Python script not writing final entry
所以我正在制作一个 Reddit 机器人,除了最后的评论 ID(用于跟踪机器人已经评论的位置)没有写入最后的条目外,它一切正常。
比如7个id中的6个写入文件,但不会写入最后一个。我是 python 的新手,所以我还在学习。
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')
主要问题是您没有调用 file.close()
函数,只是将其用作属性;添加括号以进行函数调用,这应该会将文件的其余部分刷新到磁盘。
此外,您的代码中还有一些可以改进的地方:
- 如果文件未打开(当
if keyphrase in comment.body:
为 False
时)会怎样?您可能会收到错误消息,因为文件不会打开并且 write()
调用会失败。
- 你不应该使用一个简单的
except:
子句,因为这会使调试变得困难;指定您要捕获的所有错误。
所以我正在制作一个 Reddit 机器人,除了最后的评论 ID(用于跟踪机器人已经评论的位置)没有写入最后的条目外,它一切正常。
比如7个id中的6个写入文件,但不会写入最后一个。我是 python 的新手,所以我还在学习。
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')
主要问题是您没有调用 file.close()
函数,只是将其用作属性;添加括号以进行函数调用,这应该会将文件的其余部分刷新到磁盘。
此外,您的代码中还有一些可以改进的地方:
- 如果文件未打开(当
if keyphrase in comment.body:
为False
时)会怎样?您可能会收到错误消息,因为文件不会打开并且write()
调用会失败。 - 你不应该使用一个简单的
except:
子句,因为这会使调试变得困难;指定您要捕获的所有错误。