E.R.
E.R.

Reputation: 23

Reading a file with multi pickled items from the end

I am saving information to a file using the pickle.dump function in Python 3.4. I am trying to read the data in LIFO (last in first out) form.

Alternative, I am thinking maybe there is a way I could just read the last item, assuming there is a way to point to it directly. Then point to it again and remove it from the file before reading the next item.

Thanks in advance!

Upvotes: 2

Views: 299

Answers (1)

Huang
Huang

Reputation: 609

You can keep the indices of the items and read them in a new order:

import pickle
data = ["this", "is", "your", "data"]
indices = [] # keep the index
with open("file_name.p", "wb") as f:
    for value in data:
        indices.append(f.tell())
        pickle.dump(value, f)

# you may want to store `indices` to files
# and read it in again
new_data = []
with open("file_name.p", "rb") as f:
    for ap in indices[::-1]:
        f.seek(ap)
        new_data.append(pickle.load(f))
print(new_data)

Upvotes: 1

Related Questions