Python3 File truncate() 方法、 Python3 os.closerange() 方法

Python3 File truncate() 方法


概述

truncate() 方法用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则重置到当前位置。

语法

truncate() 方法语法如下:

fileObject.truncate( [ size ])

参数

  • size -- 可选,如果存在则文件截断为 size 字节。

返回值

该方法没有返回值。

实例

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

文件 youj.txt 的内容如下:

1:www.w3cschool.cn
2:www.w3cschool.cn
3:www.w3cschool.cn
4:www.w3cschool.cn
5:www.w3cschool.cn

循环读取文件的内容:

#!/usr/bin/python3

fo = open("youj.txt", "r+")
print ("文件名: ", fo.name)

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

fo.truncate()
line = fo.readlines()
print ("读取行: %s" % (line))

# 关闭文件
fo.close()

以上实例输出结果为:

文件名:  youj.txt
读取行: 1:www.w3cschool.cn

读取行: ['2:www.w3cschool.cn\n', '3:www.w3cschool.cn\n', '4:www.w3cschool.cn\n', '5:www.w3cschool.cn\n']

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

#!/usr/bin/python3

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

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

str = fo.read()
print ("读取数据: %s" % (str))

# 关闭文件
fo.close()

以上实例输出结果为:

文件名为:  youj.txt
读取数据: 1:www.runo

Python3 os.closerange() 方法


概述

os.closerange() 方法用于关闭所有文件描述符 fd,从 fd_low (包含) 到 fd_high (不包含), 错误会忽略。

语法

closerange()方法语法格式如下:

os.closerange(fd_low, fd_high);

参数

  • fd_low -- 最小文件描述符

  • fd_high -- 最大文件描述符

该方法类似于:

for fd in xrange(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass

返回值

该方法没有返回值。

实例

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

#!/usr/bin/python3

import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 写入字符串
os.write(fd, "This is test")

# 关闭文件
os.closerange( fd, fd)

print ("关闭文件成功!!")

执行以上程序输出结果为:

关闭文件成功!!

猜你喜欢

转载自blog.csdn.net/m0_67373485/article/details/129871156
今日推荐