Python File truncate() Method
Overview
truncate()This method is used to truncate a file. If the optional parameter size is specified, the file is truncated to size characters. If size is not specified, truncate from the current position; after truncation, all characters after size are deleted.
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.
Example
The following example demonstrates the use of the truncate() method:
The content of the file example.txt is as follows:
1:www.example.com 2:www.example.com 3:www.example.com 4:www.example.com 5:www.example.com
Read the file content in a loop:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("example.txt", "r+")
print "文件名为: ", fo.name
line = fo.readline()
print "读取第一行: %s" % (line)
# 截断剩下的字符串
fo.truncate()
# 尝试再次读取数据
line = fo.readline()
print "读取数据: %s" % (line)
# 关闭文件
fo.close()
The output of the above example is:
文件名为: example.txt 读取第一行: 1:www.example.com 读取数据:
The following example truncates the example.txt file to 10 bytes:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
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.runoOther Extensions
Python File Methods