Reputation: 3
I'm a bit confused about the truncate function in python. Shouldn't the truncate function empty the file and display only the second line of input? But in my file, both the first and second input line is in the file after the program ends.
Expected output in file
Line2 input
Current output in file
Line1 input Line2 input
This is what I get in file if I use .truncate(0)
from sys import argv
script, filename = argv
print(f"Erasing the file {filename}")
print("Opening the file...")
# This empties and overrides the file when opening in w mode use 'a' to append to file
target = open(filename, 'w')
line = input("Input a line")
target.write(line)
print("Truncating ie erasing the file...")
target.truncate()
line2 = input("Input another line")
target.write(line2)
target.close()
Please help
Upvotes: 0
Views: 868