0

I am trying to print the data from external file(test.txt) after truncating it in python 3.6

But, when I try to do that with open() and read() after writing it with the write(), it is not working.

from sys import argv
script,filename=argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")

print("Opening the file...")
target=open(filename,"w")

print("Truncating the file. Goodbye!")
target.truncate()

print("Now I'm going to ask you for the three lines.")
line1=input("line 1: ")
line2=input("line 2: ")
line3=input("line 3: ")

print("I'm going to write these to the file")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
a=input("Please type the filename once again:")
b=open(a)
c=b.read()
print(c)
print("And finally, we close it.")
target.close()

Not sure, what am I doing wrong?

aadhira
  • 321
  • 1
  • 3
  • 16
  • forgot to close `target` so the changes made in inside that streambuffer hasnt been stored to disk when you open another streambuffer pointing to the same file – David Bern Jan 11 '18 at 07:18

2 Answers2

1

Python does not write to files instantly, instead holding them in a file buffer. The behaviour from Python 2 continues in Python 3, where calling the flush function on the file handle will cause it to write to the file (as per this Python 2.6 question)

Making this change should result in the behaviour you want:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
target.flush()
Ming Chia
  • 51
  • 1
  • 4
  • Its not just a `Python` "problem". As far I know, this is how OS works against the filesystem. But you are right, if you want to trigger a write before / without having a `close()` you can use a `flush` – David Bern Jan 11 '18 at 07:21
1

open and read make after the target.close(). Because once you open with target you have to close it before opens with another object.

print("I'm going to write these to the file")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
target.close()
a=input("Please type the filename once again:")
b=open(a)
c=b.read()
print(c)
print("And finally, we close it.")

try this one :)

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33