Akibur Rahman
Akibur Rahman

Reputation: 3

Python truncate function isnt working as expected

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)

enter image description here

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

Answers (1)

AKX
AKX

Reputation: 168957

See the docs, emphasis mine:

Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed.

You'll need to call .truncate(0) to truncate the file to zero bytes.

Upvotes: 1

Related Questions