0
points = str(points)
l = open("leaderboard.txt","a")
l.write(points)

I am attempting to write a value of 'points' to an external notepad file in python however the file comes out blank each time I run the program. 'points' previously was an integer value however I converted it to a string in order to store it in my file. Chances are I am missing something simple, but I cannot work it out, so any help would be much appreciated. Also, apologies for formatting errors, I am relatively new to this website.

Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
jackt04
  • 1
  • 2

4 Answers4

1

Try printing points out to make sure it is not empty.

Then make sure you close the file with l.close()

Sean Payne
  • 1,625
  • 1
  • 8
  • 20
0

You are not closing the file. This is the main reason that it is not displaying. Use l.close() at the end of your code.
A better way is to use with expression so that file is closed automatically:

points = str(points)
with open('leaderboard.txt', 'a') as l:
    l.write(points)
Code Pope
  • 5,075
  • 8
  • 26
  • 68
0

Because I/O operations are buffered in Python, you need to close the file to see the effect:

points = str(points)
l = open("leaderboard.txt","a")
l.write(points)
l.close()
Luca Schimweg
  • 747
  • 5
  • 18
0

It is a best practice to use a context manager when using open(). Setting l = open() wasn't working for me either because it wasn't being closed. This will ensure the file is properly closed without having to worry about doing it manually:

points = [(1, 1), (2, 2)]

points = str(points)
with open("leaderboard.txt","a") as file:
    file.write(points)

Output (leaderboard.txt):

[(1, 1), (2, 2)]
bherbruck
  • 2,167
  • 1
  • 6
  • 17