您现在的位置: 365建站网 > 365文章 > Python 文件 truncate() 方法(截断返回截取长度)

Python 文件 truncate() 方法(截断返回截取长度)

文章来源:365jz.com     点击数:1209    更新时间:2018-09-20 08:37   参与评论

概述

Python 文件 truncate() 方法用于截断文件并返回截断的字节长度。

指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除。

语法

truncate() 方法语法如下:

1

fileObject.truncate([size])

参数

  • size -- 可选,如果存在则文件从开头截断为指定字节。

返回值

该方法没有返回值。

实例

以下实例演示了 truncate() 方法的使用:

文件 365jz.txt 的内容如下:

1

2

3

4

5

1:www.365jz.com

2:www.365jz.com

3:www.365jz.com

4:www.365jz.com

5:www.365jz.com

循环读取文件的内容:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

#!/usr/bin/python3

 

fo = open("365jz.txt", "r+", encoding="utf-8")

# print ("文件名: ", fo.name)

 

fo.seek(36)

fo.truncate()  # 从第36个字节以后的内容全部删除了

fo.seek(0,0)

line = fo.readlines()

print("读取行: %s" % (line))

fo.truncate(10)  # 截取10个字节

fo.seek(0,0)

str = fo.read()

print("读取数据: %s" % (str))

 

# 关闭文件

fo.close()

以上实例输出结果为:

1

2

3

文件名:  365jz.txt

读取行: ['1:www.365jz.com\n', '2:www.365jz.com\n']

读取数据: 1:www.365j


假设’foo.txt‘文件中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th lineShell

以下示例显示了truncate()方法的用法。

#!/usr/bin/python3fo = open("foo.txt", "r+")print ("Name of the file: ", fo.name)line = fo.readline()print ("Read Line: %s" % (line))pos=fo.tell()print ("current position : ",pos)# Close opened filefo.close()Python

执行上面代码后,将得到以下结果 -

Name of the file:  foo.txt
Read Line: This is 1s
Read Line: []


如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (1209人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号