首页 > 解决方案 > ~~由于创建一个新文件,循环在 Python 中死去~~ 读/写问题已解决

问题描述

当我启动我的电脑时,我正在无限循环上运行一个 python 文件。该脚本将数据保存到 txt 文件中,我正在阅读它以查看我获得的数据是否已经获得。我尝试了许多不同的读/写类型,r+ w+ a+,如果文件不存在......脚本停止。我正在打印文本文件的内容,如果尚未创建,则循环不会打印任何内容。这也可能是 .read() 的问题?我尝试使用 .seek(0) 无济于事。

这是代码的文件写入部分:

def is_online_unique(streamer):
    file_contents = 'Null'
    is_online_new = False
    file_name = streamer + "Streams.txt"
    with open(r'D:\StreamerDates\\' + file_name , 'a+') as current_file:
      current_file.seek(0)

      r = requests.get(url=API_ENDPOINT+streamer, headers=head)

      data = r.text

      #print(data.replace('"', '').replace('\'', '').split(','))
      if 'type' in data and 'live' in data:
          clean_data = data.replace('"', '').replace('\'', '').split(',')
          for string in clean_data:
            if 'started_at' in string:
              date_started = string
              print("Date Started = " + date_started)
          try:
            file_contents = current_file.read()
          except:
            print('Error in reading file somehow :P')

          print("File contents:" + file_contents)
          if date_started in file_contents:
            is_online_new = False
          else:
            is_online_new = True

      if is_online_new:
        current_file.write(date_started + '\n')
      elif len(file_contents) > 500:
        if os.path.exists(r'D:\StreamerDates\\' + file_name):
          os.remove("demofile.txt")

      current_file.close()

    return is_online_new

主要:

    while(True):
      for streamer in streamers:
        if is_online_unique(streamer):
          url = 'twitch.tv/' + streamer
          #print(streamer + "\'s stream opened")
          webbrowser.get(windowsChromePath).open(url)

标签: python

解决方案


您正在打开文件

with open(r'D:\StreamerDates\\' + fileName , 'a+') as currentFile:

使用“a+”,这意味着您可以将数据附加到文件中,而不是读取,要读取您将必须有另一个

with open(r'D:\StreamerDates\\' + fileName , 'r') as currentFile:

但使用 'r' 这样您就可以读取其中的数据

您也不需要 a声明为您执行此currentFile.close()操作with


原来我在这里有点错误'a +'确实读过。 链接到模式

我认为问题在于您正在创建一个新文件,并将datestarted变量写入其中,但仅在IsOnline is True. 在文件中IsOnline时变为真。datestarted所以它永远不会写,读不会返回任何东西,这就是我认为你所看到的。它没有错,文件中没有任何内容


推荐阅读