用于在磁盘上加载字符串和文件的函数?
我有一个设计问题。我有一个用于加载图像文件的函数 loadImage() 。现在它接受一个文件路径字符串。但我也希望能够加载不在物理磁盘上的文件,例如。按程序生成。我可以让它接受一个字符串,但是它怎么知道该字符串不是文件路径而是文件数据?我可以添加一个额外的布尔参数来指定这一点,但这听起来不太干净。有什么想法吗? 现在是这样的:
def loadImage(filepath):
file = open(filepath, 'rb')
data = file.read()
# do stuff with data
另一个版本是
def loadImage(data):
# do stuff with data
如何让这个函数接受“文件路径”或“数据”并猜猜它是什么?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以更改您的
loadImage
函数以期望打开的类似文件的对象,例如:...然后从两个函数调用该函数,其中一个函数期望路径,另一个函数期望包含以下内容的字符串:数据:
You can change your
loadImage
function to expect an opened file-like object, such as:... and then have that called from two functions, one of which expects a path and the other a string that contains the data:
只创建两个函数,
loadImageFromString
和loadImageFromFile
怎么样?How about just creating two functions,
loadImageFromString
andloadImageFromFile
?这是Python,您可以轻松地区分文件名和数据字符串。我会做这样的事情:
其他方法是使用
try
块而不是使用os.path
,但该方法的本质保持不变。This being Python, you can easily distinguish between a filename and a data string. I would do something like this:
Other ways to do it would be a
try
block instead of usingos.path
, but the essence of the approach remains the same.