Easy Tutorial
❮ Python Get Dayago Python String Upper ❯

Python3 File truncate() Method

Python3 File Methods


Overview

The truncate() method is used to truncate the file starting from the first line and the first byte. It truncates the file to a specified size in bytes. If no size is provided, it truncates from the current position. After truncation, all bytes following the specified size are deleted. In Windows systems, a newline is represented by 2 bytes.

Syntax

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

fileObject.truncate([size])

Parameters

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 "tutorialpro.txt" is as follows:

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

Reading the content of the file in a loop:

#!/usr/bin/python3

fo = open("tutorialpro.txt", "r+")
print("File Name: ", fo.name)

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

fo.truncate()
line = fo.readlines()
print("Read Line: %s" % (line))

# Close the file
fo.close()

The output of the above example is:

File Name:  tutorialpro.txt
Read Line: 1:www.tutorialpro.org

Read Line: ['2:www.tutorialpro.org\n', '3:www.tutorialpro.org\n', '4:www.tutorialpro.org\n', '5:www.tutorialpro.org\n']

The following example truncates the "tutorialpro.txt" file to 10 bytes:

#!/usr/bin/python3

# Open the file
fo = open("tutorialpro.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:  tutorialpro.txt
Read Data: 1:www.runo

Python3 File Methods

❮ Python Get Dayago Python String Upper ❯