Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 File truncate() Method

Python3 File truncate() Method

Python3 File Methods Python3 File methods


Overview

truncate() The method truncates the file to size bytes starting from the first byte of the first line; without size, truncation starts at the current position. All bytes after the truncation are deleted; on Widnows a newline counts as 2 bytes. .

Syntax

The truncate() method syntax is as follows:


fileObject.truncate( [ size ])

Parameters

Return Value

This method has no return value.

Example

The following example shows how to use the truncate() method:

The contents of the runoob.txt file are as follows:


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

Read the file's contents in a loop:


#!/usr/bin/python3

fo = open("runoob.txt", "r+")
print ("文件名: ", fo.name)

line = fo.readline()
print ("读取行: %s" % (line))

fo.truncate()
line = fo.readlines()
print ("读取行: %s" % (line))

# Close file
fo.close()

The output of the above example is:


文件名:  runoob.txt
读取行: 1:www.runoob.com

读取行: ['2:www.runoob.com\n', '3:www.runoob.com\n', '4:www.runoob.com\n', '5:www.runoob.com\n']

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


#!/usr/bin/python3

# Open file
fo = open("runoob.txt", "r+")
print ("文件名为: ", fo.name)

# Truncate 10 bytes
fo.truncate(10)

str = fo.read()
print ("读取数据: %s" % (str))

# Close file
fo.close()

The output of the above example is:


文件名为:  runoob.txt
读取数据: 1:www.runo

Python3 File Methods Python3 File methods