如何在python3.x中打印txt文件中的字符串

时间:2016-03-20 15:36:16

标签: python-3.x io

好吧,我有这个脚本,它创建了一个.txt文件,并且被禁止从中打印字符串。但它什么都没打印出来(只是处理完毕,退出代码为0) ,我不知道为什么,我无法找到anwser,(我对编程很新,所以我可能不仅仅知道一些语句是如何工作的)我也使用python3.4

import io
import _pyio
import sys
import os

file1 = open("karolo.txt","w")
file3 = open("karolo.txt","r")
file1.write("abcd\n")
file34 = file3.read()
print(file34)

1 个答案:

答案 0 :(得分:0)

问题是您在数据到达文件之前尝试读取数据(它只在内部缓冲区中),请参阅this answer,了解有关将数据从内部缓冲区刷新到文件中的信息。

file1 = open("karolo.txt","w")
file3 = open("karolo.txt","r")
file1.write("abcd\n")
file1.flush()
file34 = file3.read()
print(file34)

#remember to close the files when you are done with them!
file1.close()
file3.close()

另请参阅bottom of this doc section关于使用with语句确保文件关闭的信息:

with open("karolo.txt","w") as file1, open("karolo.txt","r") as file3:
    file1.write("abcd\n")
    file1.flush()
    file34 = file3.read()

assert file1.closed and file3.closed