YouTip LogoYouTip

File Truncate

Python File truncate() Method |

Overview

The truncate() method is used to truncate a file. If the optional parameter size is specified, it indicates truncating the file to size characters. If size is not specified, truncation occurs from the current position; all characters after size are deleted after truncation.

Syntax

The syntax for the truncate() method is as follows:

fileObject.truncate( )

Parameters

  • size -- Optional. If present, the file is truncated to size bytes.

Return Value

This method does not return a value.

Example

The following example demonstrates the use of the truncate() method:

The content of the file .txt is as follows:

1:www.
2:www.
3:www.
4:www.
5:www.

Cyclically reading the file content:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Open the file
fo = open(".txt", "r+")
print("File name: "), fo.name

line = fo.readline()
print("Read the first line: %s") % (line)

# Truncate the remaining string
fo.truncate()

# Try to read data again
line = fo.readline()
print("Read data: %s") % (line)

# Close the file
fo.close()

The output of the above example is:

File name:  .txt
Read the first line: 1:www.
Read data: 

The following example truncates the first 10 bytes of the file .txt:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Open the file
fo = open(".txt", "r+")
print("File name: "), fo.name

# Truncate to 10 bytes
fo.truncate(10)

str = fo.read()
print("Read data: %s") % (str)

# Close the file
fo.close()

The output of the above example is:

File name:  .txt
Read data: 1:www.runo
← File SeekFile Seek β†’