简体   繁体   English

Python open() 在 w+ 模式下不创建文件

[英]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:我的做法是:

  1. Replace the spaces (' ') in the given string (because url's can't have spaces, duh)替换给定字符串中的空格 (' ')(因为 url 不能有空格,呵呵)
  2. use requests to get the text of the website url使用 requests 获取网站 url 的文本
  3. Create a new file and write every string you find in the website in the file.创建一个新文件并将您在网站中找到的每个字符串写入该文件。
  4. Read the file line by line and if one line has the string in it, open it in a webbrowser.逐行读取文件,如果其中一行包含字符串,请在网络浏览器中打开它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM