概述
Python 文件 truncate() 方法用于截断文件并返回截断的字节长度。
指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除。
语法
truncate() 方法语法如下:1fileObject.truncate([size])
参数size -- 可选,如果存在则文件从开头截断为指定字节。
返回值
该方法没有返回值。
实例
以下实例演示了 truncate() 方法的使用:
文件 365jz.txt 的内容如下:1
2
3
4
51:www.365jz.com
2:www.365jz.com
3:www.365jz.com
4:www.365jz.com
5:www.365jz.com
循环读取文件的内容:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17#!/usr/bin/python3
fo = open("365jz.txt", "r+", encoding="utf-8")
# print ("文件名: ", fo.name)
fo.seek(36)
fo.truncate() # 从第36个字节以后的内容全部删除了
fo.seek(0,0)
line = fo.readlines()
print("读取行: %s" % (line))
fo.truncate(10) # 截取10个字节
fo.seek(0,0)
str = fo.read()
print("读取数据: %s" % (str))
# 关闭文件
fo.close()
以上实例输出结果为:1
2
3文件名: 365jz.txt
读取行: ['1:www.365jz.com\n', '2:www.365jz.com\n']
读取数据: 1:www.365j
假设’foo.txt‘文件中包含以下行 -This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th lineShell
以下示例显示了truncate()方法的用法。#!/usr/bin/python3fo = open("foo.txt", "r+")print ("Name of the file: ", fo.name)line = fo.readline()print ("Read Line: %s" % (line))pos=fo.tell()print ("current position : ",pos)# Close opened filefo.close()Python
执行上面代码后,将得到以下结果 -Name of the file: foo.txt
Read Line: This is 1s
Read Line: []