Rewriting my scores text file to make sure it only has the Last 4 scores (python)

前端 未结 1 1518
无人及你
无人及你 2021-01-25 01:04


Previously, I had - with the help of SO users - been able to find how to store a maximum of 4 keys inside a Python Document with the maxlength property inside the dictionary

相关标签:
1条回答
  • 2021-01-25 01:58

    The writer.writerow syntax you use corresponds to the csv module, which is used in the following way:

    import csv
    with open('some_file.csv', 'wb') as csvfile:
        writer = csv.writer(csvfile, delimiter=' ',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(['Spam'] * 5 + ['Baked Beans'])
        writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
    

    It seems to me you are using some wrong reference to do this, since you are not using csv module in your code above.

    So, alter your following code

    for key, value in scores_guessed.items():
       writer.writerow([key,':',value])
    

    to this code:

    for key, value in scores_guessed.items():       
        output = "%s:%s\n" % (key,value)
        writer.write(output)
    

    Edit

    You are opening your file in binary mode, instead open it in text mode using

    writer = open('Guess Scores.txt', 'wt')
    for key, value in scores_guessed.items():       
        output = "{}:{}\n".format(key,value)
        writer.write(output)
    writer.close()
    

    EDIT 2

    Since you use deque, use:

    writer = open('Guess Scores.txt', 'wt')
    for key, value in scores_guessed.items():       
        output = "{}:{}\n".format(key,','.join(map(str, scores_guessed[key])))
        writer.write(output)
    writer.close()
    

    Or use:

    with open("output.txt", "wt") as f:
        for key in scores_guessed:
            f.write("{} {}".format(key, ','.join(map(str, scores_guessed[key]))))            
    
    0 讨论(0)
提交回复
热议问题