python-3.xio

How to print strings from a txt file in python3.x


I have this script, which creates a .txt file, and is supposed to print the string from it. But it prints out nothing(just Process finished with exit code 0)

I have no idea why and I can't find the answer, (I'm pretty new to programming so I might not just get the idea of how some statements work) also I use 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)

Solution

  • The issue is that you are trying to read the data before it reaches the file (it is only in the internal buffer) see this answer for info about flushing data out of internal buffer into the file.

    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()
    

    also see the bottom of this doc section about ensuring files get closed using a with statement:

    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