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

查看所有标签

Python Data Structures and Algorithms

Python Data Structures and Algorithms

Benjamin Baka / Packt Publishing / 2017-5-30 / USD 44.99

Key Features A step by step guide, which will provide you with a thorough discussion on the analysis and design of fundamental Python data structures.Get a better understanding of advanced Python c......一起来看看 《Python Data Structures and Algorithms》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码