Skip to content

Implement FileLikeIO

Implement FileLikeIO, a file-like object, on top of Gio's stream functionality. Additionally, a custom method for Gio.File is added, mimicking python's builtin open()

This unlocks the following functionality:

# change this path to an example file --v                         
file = Gio.File.new_for_path('/home/christoph/test.json')
with file.open_file_like('rb') as file_like:
    data = json.load(file_like)
    print(data)

The problem being solved

As you can see above, some functions (be it python internal or external libraries) expect file-like objects. This solves the problem of having a GFile from some context (e. g. a FileDialog) and bridging the gab to said functions.

Why this imlementation?

To achieve the same result there are 2 other methods:

1. Simply calling open(file)

This works with local files, but not with ones, that have no path associated (e. g. Files in a GResource or in Gvfs iirc).

2. Using io.BytesIO()

An example:

file = Gio.File.new_for_path('/home/christoph/test.json')
data = file.load_bytes(None)[0].get_data()
with io.BytesIO(data) as file_like:
    data = json.load(file_like)
    print(data)

This works with files, that have no Path associated, but has the downside of loading the whole file into memory. This isn't feasable when working with big files

This solves mentioned problem by implementing a file-like object on top of Gio functionaility.

Having the FileLikeIO available also enables the ability of mixing in FilterStreams beforehand, enabling the use of transparent compression for example. This way any consumer of PyGObject can map an arbitrary Stream as FileLike.

Edited by Christoph Matthias Kohnen

Merge request reports

Loading