黄色电影一区二区,韩国少妇自慰A片免费看,精品人妻少妇一级毛片免费蜜桃AV按摩师 ,超碰 香蕉

Python File truncate() 方法

python file truncate() 方法

python file 方法python file 方法

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

語法

truncate() 方法語法如下:

fileobject.truncate( [ size ])

參數(shù)

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

返回值

該方法沒有返回值。

實例

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

文件 codebaoku.txt 的內(nèi)容如下:

1:
2:
3:
4:
5:

循環(huán)讀取文件的內(nèi)容:

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

# 打開文件
fo = open("codebaoku.txt", "r+")
print "文件名為: ", fo.name

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

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

# 嘗試再次讀取數(shù)據(jù)
line = fo.readline()
print "讀取數(shù)據(jù): %s" % (line)

# 關(guān)閉文件
fo.close()

以上實例輸出結(jié)果為:

文件名為:  codebaoku.txt
讀取第一行: 1:

讀取數(shù)據(jù):

以下實例截取 codebaoku.txt 文件的10個字節(jié):

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

# 打開文件
fo = open("codebaoku.txt", "r+")
print "文件名為: ", fo.name

# 截取10個字節(jié)
fo.truncate(10)

str = fo.read()
print "讀取數(shù)據(jù): %s" % (str)

# 關(guān)閉文件
fo.close()

以上實例輸出結(jié)果為:

文件名為:  codebaoku.txt
讀取數(shù)據(jù): 1:www.code

python file 方法python file 方法

下一節(jié):python file write() 方法

python 教程

相關(guān)文章