python truncate是什么

2025-12-01 0 68,646

1、说明

从文件的首行首字符开始截断,截断文件为n个字符;无n表示从当前位置起截断;截断之后n后面的所有字符被删除。

2、语法

fileObject.truncate( [ size ])

3、参数

size,可选,如果存在则文件截断为 size 字节。

4、返回值

该方法没有返回值。

5、实例

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

当我们运行上面的程序,它会产生以下结果:

Name of the file: foo.txt
 
Read Line: This is 1st line
 
Read Line:

 以上就是python truncate方法的介绍,在裁剪文件方面经常会使用到,可以就这种方法先进行一个练习。更多Python学习指路:python基础教程

(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python truncate是什么 https://www.zhiup.top/1953.html

相关