Python3 File truncate() 方法
Python 3 教程
· 2019-02-07 06:26:22
概述
truncate() 方法用于从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后 V 后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。 。
语法
truncate() 方法语法如下:
fileObject.truncate( [ size ])
参数
-
size -- 可选,如果存在则文件截断为 size 字节。
返回值
该方法没有返回值。
实例
以下实例演示了 truncate() 方法的使用:
文件 codercto.txt 的内容如下:
1:www.codercto.com 2:www.codercto.com 3:www.codercto.com 4:www.codercto.com 5:www.codercto.com
循环读取文件的内容:
#!/usr/bin/python3
fo = open("codercto.txt", "r+")
print ("文件名: ", fo.name)
line = fo.readline()
print ("读取行: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("读取行: %s" % (line))
# 关闭文件
fo.close()
以上实例输出结果为:
文件名: codercto.txt 读取行: 1:www.codercto.com 读取行: ['2:www.codercto.com\n', '3:www.codercto.com\n', '4:www.codercto.com\n', '5:www.codercto.com\n']
以下实例截取 codercto.txt 文件的10个字节:
#!/usr/bin/python3
# 打开文件
fo = open("codercto.txt", "r+")
print ("文件名为: ", fo.name)
# 截取10个字节
fo.truncate(10)
str = fo.read()
print ("读取数据: %s" % (str))
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为: codercto.txt 读取数据: 1:www.runo
点击查看所有 Python 3 教程 文章: https://codercto.com/courses/l/10.html
Rationality for Mortals
Gerd Gigerenzer / Oxford University Press, USA / 2008-05-02 / USD 65.00
Gerd Gigerenzer's influential work examines the rationality of individuals not from the perspective of logic or probability, but from the point of view of adaptation to the real world of human behavio......一起来看看 《Rationality for Mortals》 这本书的介绍吧!