Matteo Secco Matteo Secco - 2 months ago 9
Python Question

I can't load multiple times a file with inside of it an empty list

I need to load more than one time a file with inside of it and empty list.
At first I tried:

import pickle
file_example = open("file.cpk","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()

def file_open():
file_open.file = open("file.pck","rb")
file_open.empty_list = pickle.load(file_open.file)
file_open.empty_list = pickle.load(file_open.file)
file_open()
file_open()


but it said "Ran out of input". I found that I have to use .seek to load more than one time the same file, so I did this:

import pickle
file_example = open("file.cpk","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()

def file_open():
file_open.file = open("file.pck","rb")
file_open.empty_list = pickle.load(file_open.file)
file_open.empty_list.seek(0)
file_open.empty_list = pickle.load(file_open.file)
file_open()


And now says "'list' object has no attribute 'seek'". How can I load more than one time that file?

Answer

You need to call seek on the file object:

import pickle
file_example = open("file.pck","wb")
empty_list = []
pickle.dump(empty_list,file_example)
file_example.close()

def file_open():
    file_open.file = open("file.pck","rb")
    file_open.empty_list = pickle.load(file_open.file)
    file_open.file.seek(0)
    file_open.empty_list = pickle.load(file_open.file)
file_open()