1

I am failing to truncate a previously created file by opening it in r+ mode given that r+ Open for reading and writing. The stream is positioned at the beginning of the file.

Reference -> here

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, 'r+')

print(target.read())

print("Truncating the file, Goodbye!")
target.truncate()
Prabhu Singh
  • 65
  • 1
  • 9

2 Answers2

4

The truncate method will resize the file so that it ends at the current file position (if you don't pass it a value for the size argument). When you read the file, you move the current position in the file from the start to the end. That means the truncation does nothing, since you're making the new end of the file the same as the old end position.

If you want to call truncate with no arguments, you need to seek back to the beginning of the file first, or alternatively, call truncate(0) to tell it to make the new file size zero bytes.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
1

The "truncate" method takes an optional size parameter. If you do not specify that parameter, it uses the default location into the file. I assume since you just read the file, the default location is at the end of the file -- so nothing follows the current location and nothing gets truncated. Try passing a zero (0) to the truncate method and see what happens. You might also try opening the file with 'rw+'.

Matt Runion
  • 1,031
  • 7
  • 13