知行编程网知行编程网  2022-12-28 01:30 知行编程网 隐藏边栏  18 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python truncate是什么的相关知识,希望可以帮到处于编程学习途中的小伙伴

什么是 python 截断


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学习指路:


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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享