python - 写入多个流的包装器

标签 python file-io

在 python 中,是否有一种简单的方法来设置一个类似文件的对象来写入,该对象实际上由多个输出流支持?例如,我想要这样的东西:

file1 = open("file1.txt", "w")
file2 = open("file2.txt", "w")
ostream = OStreamWrapper(file1, file2, sys.stdout)

#Write to both files and stdout at once:
ostream.write("ECHO!")

所以我正在寻找的是OStreamWrapper。我知道自己编写会很容易,但如果有现成的,我宁愿使用它,而不必担心查找和覆盖边缘情况。

最佳答案

class OStreamWrapper(object):

    def __init__(self, *streams):
        self.streams = list(streams)

    def write(self, string):
        for stream in self.streams:
            stream.write(string)

    def writelines(self, lines):
        # If you want to use stream.writelines(), you have
        # to convert lines into a list/tuple as it could be
        # a generator.
        for line in lines:
            for stream in self.streams:
                stream.write(line)

    def flush(self):
        for stream in self.streams:
            stream.flush()

关于python - 写入多个流的包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9130755/

相关文章:

python - 有什么办法可以使这段代码更快?

python - 继承带有外键的抽象类时出错

python - 从自动化器运行 python 脚本

c++ - 文件内容损坏的原因

python - 为什么 pythons `s.encode(' ascii', 'replace' )` 编码失败

java - 文件解析代码给了我异常而不是数字,文件写入代码给出了乱码而不是数字

MySQL DESCRIBE INTO OUTFILE 使用 Windows 命令提示符

flash - 如何使用 Flash 让我的一个类为多个平台加载声音文件?

java - 如何获取JAVA文件中最后写入的位置?

python - 如何为此 for 循环创建列表理解