Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将类似Python 2.x文件的对象移植到Python 3_Python_File_Python 3.x_Io_Porting - Fatal编程技术网

将类似Python 2.x文件的对象移植到Python 3

将类似Python 2.x文件的对象移植到Python 3,python,file,python-3.x,io,porting,Python,File,Python 3.x,Io,Porting,我正在努力改进Python3.X对的支持。它是对文件系统的抽象。每个文件系统对象都有一个open方法,该方法返回一个类似文件的对象 我面临的问题是,open方法在Python2.X上工作open,但我希望它像io.open一样工作,它返回许多二进制或文本模式流中的一个 我可以使用的是一种获取Python2.X类文件对象的方法,并返回一个适当的io流对象,该对象可以读/写底层文件类对象(但如果需要,可以处理缓冲/unicode等) 我的想法如下: def make_stream(file_obje

我正在努力改进Python3.X对的支持。它是对文件系统的抽象。每个文件系统对象都有一个open方法,该方法返回一个类似文件的对象

我面临的问题是,open方法在Python2.X上工作
open
,但我希望它像
io.open
一样工作,它返回许多二进制或文本模式流中的一个

我可以使用的是一种获取Python2.X类文件对象的方法,并返回一个适当的io流对象,该对象可以读/写底层文件类对象(但如果需要,可以处理缓冲/unicode等)

我的想法如下:

def make_stream(file_object, mode, buffering, encoding):
    # return a io instance

我看不出用stdlib做这件事有什么直接的方法。但我觉得io模块必须在幕后完成这项工作,因为它是一个提供缓冲/unicode功能的软件层。

Python2也包括同样的功能

使用“从io导入打开”中的
在Python版本中执行相同的操作

然后,您的API应该提供一个
open()
等价物(称为
open()
make\u stream()
),它使用
io
类库提供相同的功能

您只需创建一个实现的类,然后使用库提供的其他类根据需要添加缓冲和文本处理:

导入io
类MyFileObjectWrapper(io.RawIOBase):
定义初始化(self,*args):
#做需要做的事
def关闭(自我):
如果不是自动关闭:
#关闭基础文件
self.closed=True
# ... 等,以获取所需内容(例如def read(self,maxbytes=None)等。
def open(fileobj,mode='r',buffering=-1,encoding=None,errors=None,newline=None):
#从io/_iomodule.c模块改编的模式解析和验证
读取、写入、追加、更新=False
文本,二进制,通用=假
对于模式中的c:
如果c=='r':
阅读=正确;
持续
如果c=='w':
写作=真实;
持续
如果c=='a':
追加=真;
持续
如果c=='+':
更新=真;
持续
如果c=='t':
文本=真;
持续
如果c=='b':
二进制=真;
持续
如果c=='U':
普遍=阅读=正确;
持续
raise VALUERROR('无效模式:{!r}'。格式(模式))
rawmode=[]
如果读取:rawmode.append('r')
如果写入:rawmode.append('w')
如果追加:rawmode.append('a')
如果更新:rawmode.append(“+”)
rawmode=''.join(rawmode)
如果通用且(书写或附加):
raise VALUE ERROR(“不能同时使用U和写入模式”)
如果是文本和二进制){
raise VALUERROR(“不能同时使用文本和二进制模式”)
如果读取+写入+追加>1:
raise VALUETERROR(“必须正好有一个读/写/追加模式”)
如果二进制
如果编码不是无:
raise VALUERROR(“二进制模式不接受编码参数”)
如果错误不是无:
raise VALUERROR(“二进制模式不接受错误参数”)
如果换行符不是“无”:
raise VALUERROR(“二进制模式不接受换行符参数”)
raw=MyFileObjectWrapper(fileobj)
如果缓冲==1:
缓冲=-1
行缓冲=真
其他:
行缓冲=假
如果缓冲<0:
缓冲=一些合适的默认值
如果没有缓冲
如果不是二进制的:
提升值错误(“不能有无缓冲文本I/O”)
生还
如果更新:
缓冲类=io.BufferedRandom
elif书写或附加:
buffered_class=io.BufferedWriter
以英语发言:
缓冲类=io.BufferedReader
缓冲区=缓冲的\u类(原始,缓冲)
如果为二进制:
返回缓冲区
返回io.TextIOWrapper(缓冲区、编码、错误、换行、行缓冲)

上面的代码大部分改编自,但是原始文件对象被
io.RawIOBase
ABC的
MyFileObjectWrapper
子类所取代。

python2也包括同样的内容

使用“从io导入打开”中的
在Python版本中执行相同的操作

然后,您的API应该提供一个
open()
等价物(称为
open()
make\u stream()
),它使用
io
类库提供相同的功能

您只需创建一个实现的类,然后使用库提供的其他类根据需要添加缓冲和文本处理:

导入io
类MyFileObjectWrapper(io.RawIOBase):
定义初始化(self,*args):
#做需要做的事
def关闭(自我):
如果不是自动关闭:
#关闭基础文件
self.closed=True
#…等所需内容(例如def read(self,maxbytes=None)等)。
def open(fileobj,mode='r',buffering=-1,encoding=None,errors=None,newline=None):
#从io/_iomodule.c模块改编的模式解析和验证
读取、写入、追加、更新=False
文本,二进制,通用=假
对于模式中的c:
如果c=='r':
阅读=正确;
持续
如果c=='w':
写作=真实;
持续
如果c=='a':
追加=真;
持续
如果c=='+':
更新=真;
持续
如果c=='t':
文本=真;
持续
如果c=='b':
二进制=真;
持续
如果c=='U':
普遍=阅读=正确;
持续
raise VALUERROR('无效模式:{!r}'。格式(模式))
rawmode=[]
如果读取:rawmode.append('r')
如果w
import io

class MyFileObjectWrapper(io.RawIOBase):
    def __init__(self, *args):
        # do what needs done

    def close(self):
        if not self.closed:
            # close the underlying file
        self.closed = True

    # ... etc for what is needed (e.g. def read(self, maxbytes=None), etc.

def open(fileobj, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
    # Mode parsing and validation adapted from the io/_iomodule.c module
    reading, writing, appending, updating = False
    text, binary, universal = False

    for c in mode:
        if c == 'r':
            reading = True;
            continue
        if c == 'w':
            writing = True;
            continue
        if c == 'a':
            appending = True;
            continue
        if c == '+':
            updating = True;
            continue
        if c == 't':
            text = True;
            continue
        if c == 'b':
            binary = True;
            continue
        if c == 'U':
            universal = reading = True;
            continue
        raise ValueError('invalid mode: {!r}'.format(mode))

    rawmode = []
    if reading:   rawmode.append('r')
    if writing:   rawmode.append('w')
    if appending: rawmode.append('a')
    if updating:  rawmode.append('+')
    rawmode = ''.join(rawmode)

    if universal and (writing or appending):
        raise ValueError("can't use U and writing mode at once")

    if text and binary) {
        raise ValueError("can't have text and binary mode at once")

    if reading + writing + appending > 1:
        raise ValueError("must have exactly one of read/write/append mode")

    if binary
        if encoding is not None:
            raise ValueError("binary mode doesn't take an encoding argument")
        if errors is not None:
            raise ValueError("binary mode doesn't take an errors argument")
        if newline is not None:
            raise ValueError("binary mode doesn't take a newline argument")

    raw = MyFileObjectWrapper(fileobj)

    if buffering == 1:
        buffering = -1
        line_buffering = True
    else:
        line_buffering = False

    if buffering < 0:
        buffering = SOME_SUITABLE_DEFAULT

    if not buffering
        if not binary:
            raise ValueError("can't have unbuffered text I/O")

        return raw

    if updating:
        buffered_class = io.BufferedRandom
    elif writing or appending:
        buffered_class = io.BufferedWriter
    elif reading:
        buffered_class = io.BufferedReader

    buffer = buffered_class(raw, buffering)

    if binary:
        return buffer

    return io.TextIOWrapper(buffer, encoding, errors, newline, line_buffering)