[英]Python open() doesn't create a file when in w+ mode
I'm creating an application that looks into a website's text and then checks if the input string is in the url of the website's url.我正在创建一个查看网站文本的应用程序,然后检查输入字符串是否在网站 url 的 url 中。 The way I'm doing is:
我的做法是:
I hope I explained it well.我希望我解释得很好。 Here is my code:
这是我的代码:
def getGame():
game = gameEntry.get()
gameClean = game.replace(' ', '_')
print(gameClean)
gameCheck1 = requests.get('INSERT LINK HERE')
game2 = gameCheck1.text
with open('Links.txt', 'w+') as f:
f.write(game2)
readLinks = f.readlines()
for link in readLinks:
if game in link:
print(f'Found working link: {link}')
Thanks in advance.提前致谢。
When you write to the file, the file pointer ends up at the end of the file;当你写入文件时,文件指针在文件末尾结束; a subsequent read begins at the end of the file and finds nothing.
后续读取从文件末尾开始,但什么也没找到。 To fix, call
f.seek(0)
after the write
call to move the file pointer back to the beginning of the file.要修复,请在
write
调用后调用f.seek(0)
将文件指针移回文件的开头。
Also, just as a side-note, there's no reason to call .readlines()
;另外,作为旁注,没有理由调用
.readlines()
; just delete the readlines
line entirely and change the loop to:只需完全删除
readlines
行并将循环更改为:
for link in f:
and you'll read the lines on demand (instead of creating a whole list
of them up front when you only need a line at a time).并且您将按需阅读这些行(而不是在一次只需要一行时预先创建一个完整的
list
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.