Python3 File truncate() Method

Python3 File(文件) 方法Python3 File Methods


Overview

truncate()This method is used to truncate the file starting from the first byte of the first line, truncating the file to size bytes; if size is not given, truncation starts from the current position. After truncation, all bytes after V are deleted, where a newline under the Windows system represents 2 bytes.

Syntax

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

fileObject.truncate( [ size ])

Parameters

  • size-- optional; if present, the file is truncated to size bytes.

Return Value

This method has no return value.

Examples

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

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

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

Loop to read the contents of the file:

#!/usr/bin/python3

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

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

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

# 关闭文件
fo.close()

The output of the above example is:

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

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

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

#!/usr/bin/python3

# 打开文件
fo = open("example.txt", "r+")
print ("文件名为: ", fo.name)

# 截取10个字节
fo.truncate(10)

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

# 关闭文件
fo.close()

The output of the above example is:

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

Python3 File(文件) 方法Python3 File Methods

Other Extensions