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://www.codercto.com/courses/l/10.html

查看所有标签

Hadoop in Action

Hadoop in Action

Chuck Lam / Manning Publications / 2010-12-22 / USD 44.99

HIGHLIGHT Hadoop in Action is an example-rich tutorial that shows developers how to implement data-intensive distributed computing using Hadoop and the Map- Reduce framework. DESCRIPTION Hadoop i......一起来看看 《Hadoop in Action》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具