【问题标题】:How to make python continually save file io如何让python不断保存文件io
【发布时间】:2016-02-28 15:58:50
【问题描述】:

我有以下代码,

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 中按下停止按钮(在正常运行模式下)时,文件中没有任何显示,即使我每次循环时都关闭文件。有谁知道为什么或我能做些什么来解决这个问题?

【问题讨论】:

    标签: python file io stream


    【解决方案1】:

    您需要进行四项更改:

    • 在进入for循环之前打开文件——即交换with语句和for语句。

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

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

    • 不要在睡眠前关闭文件。

    顺便说一句,“success”这个词用两个 C 拼写,在 Python 中,您不必在 if 语句的控制表达式周围加上括号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2010-10-04
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多