0

Allright,i have this script, wich creates a .txt file, and is supposted to print the string from it. But it prints out nothing(just Process finished with exit code 0) , have no idea why and i can't find the anwser,(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)
czyngis
  • 413
  • 2
  • 5
  • 18
  • try `file1.close()` before opening `file3` it for reading, the contents are not correctly written to the file until it has been closed, or maybe use a `io.StringIO` to write and read from it. – Tadhg McDonald-Jensen Mar 20 '16 at 15:42
  • Thanks for the fast reply (Didin't think i'd get an anwser so fast), i did not know that nothing is really written into the file till it is closed, fixed the problem. Also, im new to stack overflow, is there a way i can mark this as solved ? Don't want to bother anybody when this is fixed already – czyngis Mar 20 '16 at 15:47
  • Welcome to stackoverflow! The speed of response really depends on who is online but I lied just a little, it doesn't write to the file until it has been [flushed](http://stackoverflow.com/questions/7127075/what-exactly-the-pythons-file-flush-is-doing),and closing a file flushes it, just look at that link if you want a more in depth explanation. (; – Tadhg McDonald-Jensen Mar 20 '16 at 15:49
  • Seems flushing is more useful than closing the file. Thanks. Anyways, i get that you just don't mark questions as solved here ? – czyngis Mar 20 '16 at 15:52
  • oh right, I will post my answer as an answer then you can [accept it](http://stackoverflow.com/help/accepted-answer). – Tadhg McDonald-Jensen Mar 20 '16 at 16:03

1 Answers1

0

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
Community
  • 1
  • 1
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59