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
Fluent Python
Luciano Ramalho / O'Reilly Media / 2015-8-20 / USD 39.99
Learn how to write idiomatic, effective Python code by leveraging its best features. Python's simplicity quickly lets you become productive with it, but this often means you aren’t using everything th......一起来看看 《Fluent Python》 这本书的介绍吧!