【问题标题】:Python File handling: standard input and outputPython 文件处理:标准输入和输出
【发布时间】:2015-12-27 20:09:51
【问题描述】:
import sys 

fileobject=open('file.txt','w')   
fileobject.write(sys.stdin.readline())
Cat

在上面的代码中,cat 执行后不应该在文件中吗?但是,当我运行它时,我发现文件为空。如果我的代码有误,有人能解释一下sys.stdin.read()sys.stdout.write() 的工作原理及其用途吗?

【问题讨论】:

    标签: file python-2.7 readline readfile


    【解决方案1】:

    你需要关闭文件

    import sys 
    
    fileobject = open('file.txt', 'w')   
    fileobject.write(sys.stdin.readline())
    Cat
    fileobject.close()
    

    如果你想在关闭文件或退出程序之前看到更新的文件内容可以使用flush():

    fileobject.flush()
    

    检查此* Question 以获得标准输入/输出

    【讨论】:

      最近更新 更多