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?

1
  • 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 Commented Jan 11, 2018 at 7:18

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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

1 Comment

Just want to point out that flush() will trigger the same write to filesystem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.