接受文件对象或路径的Python函数 [英] Python function that accepts file object or path

查看:135
本文介绍了接受文件对象或路径的Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数,接受一个字符串或文件对象的路径。到目前为止,我有:

  def awesome_parse(path_or_file):$ b $如果isinstance(path_or_file,basestring):
f = open(path_or_file,'rb')
else:
f = path_or_file
with f作为f:
返回do_stuff(f)

其中 do_stuff 需要打开的文件对象。



有没有更好的方法来做到这一点?

谢谢!

解决方案关于你的代码的奇怪的事情是,如果它传递一个打开的文件,它将关闭它。这不好。无论打开什么代码,文件都应该负责关闭它。这使得函数有点复杂,但是:

pre $ def $ awk_parse(path_or_file)
如果isinstance(path_or_file,basestring ):
f = file_to_close = open(path_or_file,'rb')
else:
f = path_or_file
file_to_close = None
try:
return do_stuff(f )
finally:
if file_to_close:
file_to_close.close()



<你可以通过编写你自己的上下文管理器来抽象出它:

  @ contextlib.contextmanager 
def awesome_open(path_or_file ):
如果isinstance(path_or_file,basestring):
f = file_to_close = open(path_or_file,'rb')
else:
f = path_or_file
file_to_close = None

try:
yield f
finally:
if file_to_close:
file_to_close.close()

def awesome_parse(path_or_file):
wi第二个awesome_open(path_or_file)作为f:
return do_stuff(f)


I want to write a function that accepts either a path as a string or a file object. So far I have:

def awesome_parse(path_or_file):
    if isinstance(path_or_file, basestring):
        f = open(path_or_file, 'rb')
    else:
        f = path_or_file
    with f as f:
        return do_stuff(f)

where do_stuff takes an open file object.

Is there a better way to do this? Does with f as f: have any repercussions?

Thanks!

解决方案

The odd thing about your code is that if it is passed an open file, it will close it. This isn't good. Whatever code opened the file should be responsible for closing it. This makes the function a bit more complex though:

def awesome_parse(path_or_file):
    if isinstance(path_or_file, basestring):
        f = file_to_close = open(path_or_file, 'rb')
    else:
        f = path_or_file
        file_to_close = None
    try:
        return do_stuff(f)
    finally:
        if file_to_close:
            file_to_close.close()

You can abstract this away by writing your own context manager:

@contextlib.contextmanager
def awesome_open(path_or_file):
    if isinstance(path_or_file, basestring):
        f = file_to_close = open(path_or_file, 'rb')
    else:
        f = path_or_file
        file_to_close = None

    try:
        yield f
    finally:
        if file_to_close:
            file_to_close.close()

def awesome_parse(path_or_file):
    with awesome_open(path_or_file) as f:
        return do_stuff(f)

这篇关于接受文件对象或路径的Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆