[英]Reading from, and then replacing all the text in a .txt file
I'm very new to Python (and coding in general, if I'm honest) and decided to learn by dipping into the Twitter API to make a weird Twitterbot that scrambles the words in a tweet and reposts them, _ebooks style. 我是Python的新手(老实说,我一般都是编码人员),因此决定学习该技术,方法是使用Twitter API,制作一个怪异的Twitterbot,将twitter中的单词打乱然后以_ebooks样式重新发布。
Anyway, the way I have it currently set up, it pulls the latest tweet and then compares it to a .txt file with the previous tweet. 无论如何,以我当前设置的方式,它会提取最新的tweet,然后将其与具有先前tweet的.txt文件进行比较。 If the tweet and the .txt file match (ie, not a new tweet), it does nothing.
如果tweet和.txt文件匹配(即不是新的tweet),则不执行任何操作。 If they don't, it replaces the .txt file with the current tweet, then scrambles and posts it.
如果没有,它将用当前的推文替换.txt文件,然后进行加扰并将其发布。 I feel like there's got to be a better way to do this than what I'm doing.
我觉得必须有比我正在做的更好的方法。 Here's the relevant code:
以下是相关代码:
words = hank[0]['text']
target = open("hank.txt", "r")
if words == "STOP":
print "Sam says stop :'("
return
else:
if words == target.read():
print "Nothing New."
else:
target.close()
target = open("hank.txt", "w")
target.write(words)
target.close()
Obviously, opening as 'r' just to check it against the tweet, closing, and re-opening as 'w' is not very efficient. 显然,以“ r”打开只是为了对照推文检查它,然后关闭并以“ w”重新打开不是很有效。 However, if I open as 'w+' it deletes all the contents of the file when I read it, and if I open it as 'r+', it adds the new tweet either to the beginning or the end of the file (dependent on where I set the pointer, obviously).
但是,如果我以“ w +”打开,则在读取文件时会删除文件的所有内容;如果以“ r +”打开,则会将新的推文添加到文件的开头或结尾(取决于我在哪里设置指针,很明显)。 I am 100% sure I am missing something TOTALLY obvious, but after hours of googling and dredging through Python documentation, I haven't found anything simpler.
我100%肯定完全看不到某些东西,但是经过数小时的搜索和挖掘Python文档后,我发现没有任何更简单的东西了。 Any help would be more than welcome haha.
任何帮助都将超过欢迎哈哈。 :)
:)
I suggest you use yield
to compare hank.txt and words line by line so that more memory space could be saved, if you are so focused on efficiency. 我建议您使用
yield
来逐行比较hank.txt和单词,以便在您专注于效率的情况下节省更多的内存空间。 As for file operation, I don't think there is a better way in overwriting a file. 至于文件操作,我认为没有更好的方法来覆盖文件。 If you are using Linux, maybe 'cat > hank.txt' could be faster.
如果您使用的是Linux,则“ cat> hank.txt”可能更快。 Just a guess.
只是一个猜测。
with open(filename, "r+") as f: data = f.read()// Redaing the data //any comparison of tweets etc.. f.truncate()//here basically it clears the file. f.seek(0)// setting the pointer f.write("most recent tweet")// writing to the file
No need to close the file instance, it automatically closes. 无需关闭文件实例,它会自动关闭。 Just read python docs on these methods used for a more clear picture.
只需阅读有关这些方法的python文档即可获得更清晰的画面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.