开发者

function for loading both strings and files on disk?

开发者 https://www.devze.com 2023-04-13 02:25 出处:网络
I have a design question. I have a function loadImage() for loading an image file. Now it accepts a string which is a file path. But I also want to be able to load files which are not on physical disk

I have a design question. I have a function loadImage() for loading an image file. Now it accepts a string which is a file path. But I also want to be able to load files which are not on physical disk, eg. generated procedurally. I could have it accept a string, but then how could it know the string is not a file path but file data? I could add an extra boolean argument to specify that, but that doesn't sound very clean. Any ideas? It's开发者_如何学JAVA something like this now:

def loadImage(filepath):
    file = open(filepath, 'rb')
    data = file.read()
    # do stuff with data

The other version would be

def loadImage(data):
    # do stuff with data

How to have this function accept both 'filepath' or 'data' and guess what it is?


You can change your loadImage function to expect an opened file-like object, such as:

def load_image(f):
    data = file.read()

... and then have that called from two functions, one of which expects a path and the other a string that contains the data:

from StringIO import StringIO

def load_image_from_path(path):
    with open(path, 'rb') as f:
        load_image(f)

def load_image_from_string(s):
    sio = StringIO(s)
    try:
        load_image(sio)
    finally:
        sio.close()


How about just creating two functions, loadImageFromString and loadImageFromFile?


This being Python, you can easily distinguish between a filename and a data string. I would do something like this:

import os.path as P
from StringIO import StringIO
def load_image(im):
    fin = None
    if P.isfile(im):
        fin = open(im, 'rb')
    else:
        fin = StringIO(im)

    # Read from fin like you would from any open file object

Other ways to do it would be a try block instead of using os.path, but the essence of the approach remains the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消