Latest web development tutorials

Python File truncate () method

Python File (File) method Python File (File) method


Outline

truncate () method is used to truncate the file, if you specify the optional parameter size, said truncated file size characters.If you do not specify a size, cut off from the current position; all the characters behind the size after truncation are deleted.

grammar

truncate () method has the following syntax:

fileObject.truncate( [ size ])

parameter

  • size - Alternatively, if the file exists truncated to size bytes.

return value

This method has no return value.

Examples

The following example demonstrates the use truncate () method:

W3big.txt content file as follows:

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

Loop reads the contents of the file:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

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

# 截断剩下的字符串
fo.truncate()

# 尝试再次读取数据
line = fo.readline()
print "读取数据: %s" % (line)

# 关闭文件
fo.close()

The above example output is:

文件名为:  w3big.txt
读取第一行: 1:www.w3big.com

读取数据:

The following examples interception 10 bytes w3big.txt file:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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

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

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

# 关闭文件
fo.close()

The above example output is:

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

Python File (File) method Python File (File) method