简体   繁体   中英

How to serialize and deserialize an open file object?

Is there a way to serialize and deserialize an open file-object, such that the deserialized object is an object with same characteristics as the serialized one (ie, full-path, opening mode, offset, internal buffers, etc.)?

Code-wise, it would be something like that:

import some_pickle_like_module as splm

with open("infile.bin", "rb") as fp:
    first17bytes = fp.read(17)

    with open("infile.splm", "wb") as pkl:
        splm.dump(fp, pkl)

# and later in the code:

with open("infile.splm", "rb") as pkl:
    fp = splm.load(pkl)

next17bytes = fp.read(17)
fp.close()

Note that this example is somewhat trivial (because I could dump() and load() the file's name and offset), but the same could apply to compressed files, where seeking to a given location could be very slow.

No, it's not possible. Proof: if you close the file-descriptor there is no way to reobtain the old object from unpickling without re-opening the file. File objects are defined by the OS kernel and python doesn't have control on that, and thus cannot pickle them. The only way is to pickle the path, mode and byte offset and, when unpickling, re-open the file and move to the correct position.

In any case I don't think it's a good idea to pickle files at all, because the file might be deleted and the unpickling would fail. Just pickle/unpickle the contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM