【问题标题】:Closing a file with stdout being written to it关闭一个正在写入标准输出的文件
【发布时间】:2014-05-04 22:28:28
【问题描述】:

假设我正在将stdout 写入文件,如下所示:

sys.stdout = open("file.txt", "w")
# print stuff here

这样做是行不通的:

sys.stdout.close()

写入stdout 后如何关闭文件?

【问题讨论】:

  • 保留对文件对象的引用,然后在该引用上调用.close()
  • 为什么with 不符合您的要求?您的示例将其打开到read,但是当您完成该with 块时它会自动关闭。
  • 什么操作系统?你的问题真的没有意义。您的意思是“如何停止将标准输出写入文件”?
  • 仅仅因为它'看起来不像我正在尝试做的事情'并不意味着它没有做你想做的事情。因为按照措辞,它绝对是。

标签: python file stdout


【解决方案1】:

我将您的问题理解为:“如何将sys.stdout 重定向到文件?”

import sys

# we need this to restore our sys.stdout later on
org_stdout = sys.stdout

# we open a file
f = open("test.txt", "w")
# we redirect standard out to the file
sys.stdout = f
# now everything that would normally go to stdout
# now will be written to "test.txt"
print "Hello world!\n"
# we have no output because our print statement is redirected to "test.txt"!
# now we redirect the original stdout to sys.stdout
# to make our program behave normal again
sys.stdout = org_stdout
# we close the file
f.close()
print "Now this prints to the screen again!"
# output "Now this prints to the screen again!"

# we check our file
with open("test.txt") as f:
    print f.read()
# output: Hello World!

这是对您问题的回答吗?

【讨论】:

    【解决方案2】:

    如果你想将所有 print() 重定向到一个文件,你也可以这样做,这是一种快速的方法,在我看来也很有用,但它可能会产生其他影响。如果我错了,请纠正我。

    import sys
    
    stdoutold = sys.stdout
    sys.stdout = fd = open('/path/to/file.txt','w')
    # From here every print will be redirected to the file
    sys.stdout = stdoutold
    fd.close()
    # From here every print will be redirected to console
    

    【讨论】:

    • 简单且为我工作
    【解决方案3】:

    你可以这样做:

    import sys
    
    class writer(object):
        """ Writes to a file """
    
        def __init__(self, file_name):
            self.output_file = file_name
    
        def write(self, something):
            with open(self.output_file, "a") as f:
                f.write(something)
    
    if __name__ == "__main__":
        stdout_to_file = writer("out.txt")
        sys.stdout = stdout_to_file
        print "noel rocks"
    

    文件只有在你这样写时才会打开。

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2011-04-09
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多