Python File truncate() 方法

Python 教程 · 2019-02-03 16:12:52

概述

truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。

语法

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/python
# -*- coding: UTF-8 -*-

# 打开文件
fo = open("codercto.txt", "r+")
print "文件名为: ", fo.name

line = fo.readline()
print "读取第一行: %s" % (line)

# 截断剩下的字符串
fo.truncate()

# 尝试再次读取数据
line = fo.readline()
print "读取数据: %s" % (line)

# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  codercto.txt
读取第一行: 1:www.codercto.com

读取数据:

以下实例截取 codercto.txt 文件的10个字节:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开文件
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 教程 文章: https://codercto.com/courses/l/8.html

查看所有标签

Coding the Matrix

Coding the Matrix

Philip N. Klein / Newtonian Press / 2013-7-26 / $35.00

An engaging introduction to vectors and matrices and the algorithms that operate on them, intended for the student who knows how to program. Mathematical concepts and computational problems are motiva......一起来看看 《Coding the Matrix》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具