Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom filetype in Python 3

How to start creating my own filetype in Python ? I have a design in mind but how to pack my data into a file with a specific format ?

For example I would like my fileformat to be a mix of an archive ( like other format such as zip, apk, jar, etc etc, they are basically all archives ) with some room for packed files, plus a section of the file containing settings and serialized data that will not be accessed by an archive-manager application.

My requirement for this is about doing all this with the default modules for Cpython, without external modules.

I know that this can be long to explain and do, but I can't see how to start this in Python 3.x with Cpython.

like image 601
juio Avatar asked Oct 22 '22 13:10

juio


1 Answers

Try this:

from zipfile import ZipFile
import json

data = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])

with ZipFile('foo.filetype', 'w') as myzip:
    myzip.writestr('digest.json', data)

The file is now a zip archive with a json file (thats easy to read in again in many lannguages) for data you can add files to the archive with myzip write or writestr. You can read data back with:

with ZipFile('foo.filetype', 'r') as myzip:
    json_data_read = myzip.read('digest.json')
    newdata = json.loads(json_data_read)

Edit: you can append arbitrary data to the file with:

f = open('foo.filetype', 'a')
f.write(data)
f.close()

this works for winrar but python can no longer process the zipfile.

like image 132
joojaa Avatar answered Oct 27 '22 10:10

joojaa