File函数 中的 file.truncate([size])

首页 / Python2入门教程 / File函数 中的 file.truncate([size])

Python file方法truncate()截断文件的大小。如果存在可选的size参数,文件将被截断为(至多)该大小。

大小默认为当前位置。当前文件位置不变。请注意,如果指定的size超过文件的当前大小,则输出取决于平台。

注意-如果文件以只读模式打开,此方法将不起作用。

file.truncate([size]) - 语法

fileObject.truncate( [ size ])
  • size  -  如果存在此可选参数,文件将被截断为(至多)该大小。

file.truncate([size]) - 返回值

此方法不返回任何值。

file.truncate([size]) - 示例

以下示例显示truncate()方法的用法。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python

# Open a file
fo=open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line=fo.readline()
print "Read Line: %s" % (line)

# Now truncate remaining file.
fo.truncate()

# Try to read file now
line=fo.readline()
print "Read Line: %s" % (line)

# Close opend file
fo.close()

当无涯教程运行上面的程序时,它产生以下输出-

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-truncate.html

来源:LearnFk无涯教程网

Name of the file:  foo.txt

Read Line:

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

数据结构与算法之美 -〔王争〕

如何做好一场技术演讲 -〔极客时间〕

高并发系统设计40问 -〔唐扬〕

DDD实战课 -〔欧创新〕

MongoDB高手课 -〔唐建法(TJ)〕

摄影入门课 -〔小麥〕

成为AI产品经理 -〔刘海丰〕

搞定音频技术 -〔冯建元 〕

给程序员的写作课 -〔高磊〕

好记忆不如烂笔头。留下您的足迹吧 :)