跳到主要内容

Python3 File truncate() 方法

Python3 File truncate() 方法

概述

truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则重置到当前位置。

语法

truncate() 方法语法如下:

fileObject.truncate( [ size ])

参数

  • size -- 可选,如果存在则文件截断为 size 字节。

返回值

该方法没有返回值。

实例

以下实例演示了 truncate() 方法的使用:

文件 youj.txt 的内容如下:

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

循环读取文件的内容:

#!/usr/bin/python3

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

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

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

# 关闭文件
fo.close()

以上实例输出结果为:

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

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

以下实例截取 youj.txt 文件的10个字节:

#!/usr/bin/python3

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

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

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

# 关闭文件
fo.close()

以上实例输出结果为:

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