-1

What can the parentheses after the function .truncate() be used for? I tried putting different numbers in there to see if it would only truncate that amount of characters, but it always truncated the entire file.

from sys import argv

script, filename = argv
opened_writable_file = open(filename, "w")
opened_writable_file.truncate(2)

1 Answers1

0

The method truncate() truncates the file's size. Size is a parameter send to the function. If the optional size argument is present, the file is truncated to (at most) that size.

The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file's current size, the result is platform-dependent.

Reference: http://www.tutorialspoint.com/python/file_truncate.htm

With truncate(), you can declare how much of the file you want to remove, based on where you're currently at in the file. Without parameters, truncate() acts like w, whereas w always just wipes the whole file clean. So, these two methods can act identically, but they don't necessarily.

Reference: Why truncate when we open a file in 'w' mode in python

truncate() function does this: ...it only "empties the file" if the current position is the start of the file—but since we just opened the file (and not in a mode), the current position is the start, so that isn't relevant. We're truncating to an empty file.

Reference: Behaviour of truncate() method in Python

Community
  • 1
  • 1
Erba Aitbayev
  • 4,167
  • 12
  • 46
  • 81
  • I don't understand. I assumed that the parentheses where to declare how much of the file i wanted to truncate, but no matter what number i put there it truncated the entire file – pancake man Jan 28 '16 at 19:59