Latest web development tutorials

Python File truncate() 方法

Python File(文件) 方法 Python File(文件)方法


概述

truncate()方法用於截斷文件,如果指定了可選參數size,則表示截斷文件為size個字符。如果沒有指定size,則從當前位置起截斷;截斷之後size 後面的所有字符被刪除。

語法

truncate() 方法語法如下:

fileObject.truncate( [ size ])

參數

  • size --可選,如果存在則文件截斷為size字節。

返回值

該方法沒有返回值。

實例

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

文件w3big.txt 的內容如下:

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

循環讀取文件的內容:

#!/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()

以上實例輸出結果為:

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

读取数据:

以下實例截取w3big.txt 文件的10個字節:

#!/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()

以上實例輸出結果為:

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

Python File(文件) 方法 Python File(文件)方法