File Methods
truncate()
Resize the file stream to the specified byte size.
file.truncate(size=None)
file.truncate() resizes the file to at most size bytes.
If size is omitted, it truncates the file at the current stream position (from tell()).
Parameters
| Name | Description |
|---|---|
| size | Optional target size in bytes. Defaults to current file position. |
Returns
The new file size in bytes.
Try it
Run it and change it
import tempfile
with tempfile.NamedTemporaryFile(mode='w+', delete=True) as f:
f.write('Hello World!')
f.truncate(5)
f.seek(0)
print(f.read())Worth knowing
- Requires write mode: The file must be opened in a mode that permits writing (e.g.
'r+','w','a').