python - 如何在 Python 函数中同时接受文件名和类文件对象?

标签 python file-io

在我的代码中,我有一个 load_dataset 函数,它读取文本文件并进行一些处理。最近我考虑添加对类文件对象的支持,我想知道最好的方法。目前我有两种实现方式:

首先,类型检查:

if isinstance(inputelement, basestring):
   # open file, processing etc
# or
# elif hasattr(inputelement, "read"):
elif isinstance(inputelement, file):
   # Do something else

或者,两个不同的论点:

def load_dataset(filename=None, stream=None):
    if filename is not None and stream is None:
        # open file etc
    elif stream is not None and filename is None:
        # do something else

然而,这两种解决方案都不能说服我太多,尤其是第二种,因为我看到了太多的陷阱。

将类文件对象或字符串接收到进行文本读取的函数中的最简洁(也是最 Pythonic)的方法是什么?

最佳答案

将文件名或类似文件的对象作为参数的一种方法是实现 context manager可以处理两者。可以找到一个实现 here ,为了一个独立的答案,我引用:

class open_filename(object):
"""Context manager that opens a filename and closes it on exit, but does
nothing for file-like objects.
"""
def __init__(self, filename, *args, **kwargs):
    self.closing = kwargs.pop('closing', False)
    if isinstance(filename, basestring):
        self.fh = open(filename, *args, **kwargs)
        self.closing = True
    else:
        self.fh = filename

def __enter__(self):
    return self.fh

def __exit__(self, exc_type, exc_val, exc_tb):
    if self.closing:
        self.fh.close()

    return False

可能的用法:

def load_dataset(file_):
    with open_filename(file_, "r") as f:
        # process here, read only if the file_ is a string

关于python - 如何在 Python 函数中同时接受文件名和类文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268353/

相关文章:

python - 从元素/节点中提取 HTML

Python file.read() 在文件开头看到垃圾字符

postgresql - HAProxy 拆分读/写 postgresql

python - 如何在tensorflow中加载本地镜像?

python - 在这个 python 代码中产生 "TypeError character mapping must return integer..."是什么?

python - 如何将中间件添加到 App Engine 网络应用程序框架?

c - 使用 fwrite() 在 C 中覆盖 ID3v2 标记

使用 read()、write()、open() 将文件内容复制到另一个文件

c++ - ios 无法识别

具有属性的Python xmltodict强制数组