Sepehr Sobhani
Sepehr Sobhani

Reputation: 882

How to make python continually save file io

I have the following code,

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)

The problem I am having is that when I press the stop button in pycharm(in normal running mode)nothing shows up in the file, even tho I am closing the file every time I loop. Does anybody know why or what i can do to fix this?

Upvotes: 1

Views: 192

Answers (1)

zwol
zwol

Reputation: 140758

You need to make four changes:

  • Open the file before entering the for loop -- that is, swap the with statement and the for statement.

  • Open the file in "a" mode instead of "w" mode. "a" stands for "append". Right now, every time you reopen the file it erases everything you wrote to it before.

  • Call file.flush() immediately after file.write() (that is, before the if SucessCount % 5 == 0.)

  • Don't close the file before sleeping.

Incidentally, the word "success" is spelled with two Cs, and in Python you do not have to put parentheses around the controlling expression of an if statement.

Upvotes: 1

Related Questions