如何让python不断保存文件io

How to make python continually save file io

我有以下代码,

def main():



    SucessCount = 0
    line = []
    StringList = ''


    url = "https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=&match_id=1957663499"
    http = urllib3.PoolManager()

    for i in range(1860878309, 1860878309 + 99999999999999999 ):
        with open("DotaResults.txt", "w") as file:
            if SucessCount > 70000:
                break
            result = http.request('GET', 'https://api.steampowered.com/IDOTA2Match_570/GetMatchDetails/V001/?key=F878695BB3657028B92BCA60CEA03E16&match_id=' + str(i))
            x = json.loads(result.data.decode('utf-8'))



            if('error' in x['result']):
                print("Not found")
            else:
                if validityCheck(x['result']['players']) == True and x['result']['game_mode'] == 22:

                    line = vectorList(x)
                    #print(line.count(1))
                    if(line.count(1) == 10 or line.count(1) == 11):
                        SucessCount += 1
                        print('Ok = ' + str(SucessCount))
                        print("MatchId = " + str(x['result']['match_id']))
                        StringList = ','.join([str(i) for i in line])
                        file.write(StringList + '\n')

                        if(SucessCount % 5 == 0):

                            file.flush()
                            file.close()
                            time.sleep(30)

我遇到的问题是,当我在 pycharm(在正常 运行 模式下)按下停止按钮时,文件中没有显示任何内容,即使我每次都关闭文件我循环。有人知道为什么或我能做些什么来解决这个问题吗?

您需要进行四处更改:

  • 在进入 for 循环之前打开文件——也就是说,交换 with 语句和 for 语句。

  • 以 "a" 模式而不是 "w" 模式打开文件。 "a" 代表 "append"。现在,每次您重新打开文件时,它都会删除您之前写入的所有内容。

  • file.write()之后(即在if SucessCount % 5 == 0之前)立即调用file.flush()

  • 睡觉前不要关闭文件。

顺便说一下,单词 "success" 拼写有两个 C,在 Python 中,您不必在 if 语句的控制表达式两边加上括号。