Question

I got this function:

  def restapuntos(precio, usuario ,saladondeocurre):
    print("Function started")
    data = []
    with open("listas\estadisticas\Trivial-"+saladondeocurre+".txt", "r+") as f:
      for line in f:
        data_line = json.loads(line)
        if data_line[0] == usuario:
          print("User: "+user.name+", removing "+str(precio)+" from "+str(data_line[1]))
          data_line[1] = data_line[1]-precio
        data.append(data_line)
      f.seek(0)
      f.writelines(["%s\n" % json.dumps(i) for i in data])
      f.truncate()
    print("Function has been used")

Which is called with:

Myclass.restapuntos(10, user.name, room.name)

And the 3 prints tell me this:

Function started
User: saelyth, removing 10 from 461
Function has been used

But here is the problem: The file wasn't updated, it still shows 461 instead of 451 despite that all seems to work fine and the print actually knows what to do without errors, the info in the file is still the same as before after I run the code.

Anyone knows why?

Was it helpful?

Solution 2

doh i forgot to update this thread, but i managed to find the issue, somehow the name of the var "data" was creating an issue, no idea why... and as soon as i changed it all went right.

OTHER TIPS

To my understanding, you have to close the file in order to have the data update so for example, I have the file "xyz.txt" in my C drive:

x = open("C:\\xyz.txt", "r+")
x.read()
x.write("test")
x.close()

before running x.close(), the file will be empty.

Note: use two backslashes (\\) or put "r" before a string (r"tes\t") to prevent accidental escape codes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top