Python File truncate() method
Overview
truncate() This method truncates the file. If the optional parameter size is specified, the file is truncated to size characters. If size is not specified, truncation starts from the current position; after truncation, all characters beyond size are deleted.
Syntax
The truncate() method syntax 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 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/python
# -*- coding: UTF-8 -*-
# Open file
fo = open("runoob.txt", "r+")
print "文件名为: ", fo.name
line = fo.readline()
print "读取第一行: %s" % (line)
# Truncate the remaining string
fo.truncate()
# Try reading the data again
line = fo.readline()
print "读取数据: %s" % (line)
# Close file
fo.close()
The output of the above example is:
文件名为: runoob.txt
读取第一行: 1:www.runoob.com
Read data:
The following example truncates the runoob.txt file to 10 bytes:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 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
Python File methods