统一处理来自文件或字符串的Unicode/非Unicode数据。
data的Python项目详细描述
data是一个小的python模块,它允许您以单一的形式处理输入 方法并让调用方提供字节字符串、Unicode对象、 类似文件或文件名。
>>>open('helloworld.txt','w').write('hello, world from a file')>>>fromdataimportDataasI>>>a=I(u'hello, world')>>>b=I(file='helloworld.txt')>>>c=I(open('helloworld.txt'))>>>printunicode(a)hello,world>>>printunicode(b)hello,worldfromafile>>>printunicode(c)hello,worldfromafile
使用datadecorator可以使这更加方便:
>>>fromdata.decoratorsimportdata>>>@data('buf')...defparse_buffer(buf,magic_mode=False):...return'buf passed in as '+repr(buf)...>>>parse_buffer('hello')"buf passed in as Data(data='hello', encoding='utf8')">>>rv=parse_buffer(open('helloworld.txt'))>>>assert'file='inrv
安装
所有实例都支持像read或__str__这样的方法,这些方法使 将其放入现有API中:
>>>d=I('some data')>>>d.read(4)u'some'>>>d.read(4)u' dat'>>>d.read(4)u'a'>>>e=I(u'more data')>>>str(e)'more data'
注意read如何返回unicode。此外,readb还提供:
>>>f=I(u'I am \xdcnicode.')>>>f.readb()'I am \xc3\x9cnicode.'
每个data对象都有一个用于转换的编码属性 从和到Unicode。
>>>g=I(u'I am \xdcnicode.',encoding='latin1')>>>g.readb()'I am \xdcnicode.'
还支持迭代和行读取:
>>>h=I('I am\nof many\nlines')>>>h.readline()u'I am\n'>>>h.readlines()[u'of many\n',u'lines']>>>i=I('line one\nline two\n')>>>list(iter(i))[u'line one\n',u'line two\n']
额外费用
保存到
提供了一些有用的方便方法:
>>>j=I('example')>>>j.save_to('example.txt')
save_to方法将使用最有效的方法来保存 数据到文件(copyfileobj或write())。也可以通过 类文件对象:
>>>k=I('example2')>>>withopen('example2.txt','wb')asout:...k.save_to(out)...
保存的温度
如果需要安全临时文件中的输出,temp_saved 可用:
>>>l=I('goes into tmp')>>>withl.temp_saved()astmp:...printtmp.name.startswith('/tmp/tmp')...printl.read()...Truegoesintotmp
temp_saved函数几乎与tempfile.NamedTemporaryFile相同, 有一点不同:这里没有delete参数。文件只被删除 当上下文管理器退出时。
有用的地方
data可以在api的两边使用,也可以在传入值时使用:
>>>importjson>>>fromdataimportDataasI>>>m=I('{"this": "json"}')>>>json.load(m){u'this':u'json'}
或者在获取传递的值时(请参见上面的数据装饰器示例)。如果 必要时,您还可以支持允许用户传入文件名的api:
>>>classParser(object):...@data('input')...defparse(self,input,parser_opt=False):...returninput...defparse_file(self,input_file,*args,**kwargs):...returnself.parse(I(file=input_file),*args,**kwargs)...>>>p=Parser()>>>p.parse_file('/dev/urandom')Data(file='/dev/urandom',encoding='utf8')
有关api引用,请参阅http://pythonhosted.org/data上的文档。