简体   繁体   English

创建一个像对象 python 建议这样的自定义文件?

[英]Creating a custom file like object python suggestions?

Hi i am looking to implement my own custom file like object for an internal binary format we use at work(i don't really want to go into too much detail because i don't know if i can).嗨,我希望为我们在工作中使用的内部二进制格式实现我自己的自定义文件,如对象(我真的不想详细介绍,因为我不知道我是否可以)。 I am trying to go for a more pythonic way of doing things since currently we have two functions read/write(each ~4k lines of code) which do everything.我正在尝试采用更 Pythonic 的做事方式,因为目前我们有两个函数读/写(每个约 4k 行代码)可以做所有事情。 However we need more control/finesse hence the fact of me rewriting this stuff.然而,我们需要更多的控制/技巧,因此我重写了这些东西。

I looked at the python documentation and they say what methods i need to implement, but don't mention stuff like iter () / etc.我查看了 python 文档,他们说我需要实现哪些方法,但没有提到诸如iter () / 之类的东西。

Basically what i would love to do is stuff like this:基本上我想做的是这样的事情:

output_file_objs = [
    open("blah.txt", "w")
    open("blah142.txt", "wb")
    my_lib.open("internal_file.something", "wb", ignore_something=True)
]

data_to_write = <data>

for f in output_file_objs:
    f.write(data_to_write)

So i can mix it in with the others, and basically have a level of transparency.所以我可以把它和其他的混合在一起,基本上有一定程度的透明度。 I will add custom methods to it, but thats not a problem.我会向它添加自定义方法,但这不是问题。

Is there any sort of good reference regarding writing your own custom file like objects?关于编写自己的自定义文件(如对象),是否有任何好的参考? Like any form of restrictions or special methods ( iter ).像任何形式的限制或特殊方法( iter )。 I should implement?我应该执行吗?

Or is there a good example of one from within the python standard library that i can look at?或者我可以查看python标准库中的一个很好的例子吗?

What makes up a "file-like" actually depends on what you intend to use it for;什么构成“类文件”实际上取决于您打算将其用于什么目的; not all methods are required to be implemented (or to have a sane implementation).并非所有方法都需要实现(或有一个健全的实现)。

Having said that, the file and iterator docs are what you want.话虽如此, file迭代器文档正是您想要的。

Why not stuff your data in StringIO?为什么不在 StringIO 中填充您的数据? Otherwise, you can look at the documentation and implement all of the file like methods.否则,您可以查看文档并实现所有文件之类的方法。 Truth be told, there are no real interfaces in Python, and some features (like tell()) may not make sense for your files, so you can leave them unimplemented.说实话,Python 中没有真正的接口,并且某些功能(如 tell())可能对您的文件没有意义,因此您可以不实施它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM