1

I was working on a saving mechanic for a game I am making, and kept getting the error _pickle.UnpicklingError: could not find MARK. I checked the data it was producing and noticed that it was creating a new line near the end of the data, and because I am reading line by line that broke everything. I tried the solution from this answer. This solved my problem temporarily, but now the error has returned, and changing the variable names isn't helping. This is my code for saving:

with open("pastgames", "ab") as file:

     data = []
     tempdata = []

     #for all the data write it to a list then pickle that list and put it in a file
     for i in rownums:
          tempdata.append(i.nums)
     data.append(tempdata)
     tempdata = []
     for x in dots:
          tempdata.append(x.color)
     data.append(tempdata)
     data.append(combo)
     data.append((time.year, time.month, time.day, time.hour, time.minute))


     dumpdata = pickle.dumps(data)
     file.write(dumpdata + b"\n")

And this is my code for reading:

with open("pastgames", "rb") as file:

     content = file.readlines()
     data = pickle.loads(content[dataind])

More code can be found at this GitHub repo. Apologies if my code is hard to read, help with that would be much appreciated.

Thank you in advance

**Update: ** So I found the issue, it doesn't work at 10 o'clock. The way I am formatting the data creates a 0A byte, which it mistakes for a newline character. I saw some comments about just using pickle.load(file) but that just ended up returning the first item in the data file. More help on that would be much appreciated. Thanks!

  • Update: it's working now but I want to make sure this error doesn't happen again and why it's doing this – user17493432 Apr 05 '22 at 20:47
  • 2
    I am not sure, perhaps readlines does not make sense for a binary file? What if there is a \n charachter somewhere in the binary dump, wouldn't that confuse the readline() method? – Ant Apr 05 '22 at 20:50
  • I don't think you need any sort of delimiter between pickles written to the same file. Just call `pickle.load()` directly on the file, and it will read a single object. (`readline()` on a binary file is meaningless.) – jasonharper Apr 05 '22 at 20:52
  • If "that just ended up returning the date" means "returning the _data_", then this is exactly what `pickle` does: it serializes data to a file and then reads the same object back. Saving "line by line" in a binary file doesn't make sense because binary files don't have the concept of a "line" - it's all just a stream of bytes. – ForceBru Apr 06 '22 at 16:42
  • @ForceBru Nope, I should've elaborated on that, it returns the last item in the data. I've been messing around with it since then and now it just returns the first data item rather than the desired one. – user17493432 Apr 06 '22 at 16:49

0 Answers0