Latest web development tutorials

Python3 os.ftruncate() 方法

Python3 OS 文件/目錄方法 Python3 OS文件/目錄方法


概述

os.ftruncate() 裁剪文件描述符fd對應的文件, 它最大不能超過文件大小。

Unix上可用。

語法

ftruncate()方法語法格式如下:

os.ftruncate(fd, length)¶

參數

  • fd --文件的描述符。

  • length --要裁剪文件大小。

返回值

該方法沒有返回值。

實例

以下實例演示了ftruncate() 方法的使用:

#!/usr/bin/python3

import os, sys

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

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

# 使用 ftruncate() 方法
os.ftruncate(fd, 10)

# 读取内容
os.lseek(fd, 0, 0)
str = os.read(fd, 100)
print ("读取的字符串是 : ", str)

# 关闭文件
os.close( fd)

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

執行以上程序輸出結果為:

读取的字符串是 :  This is te
关闭文件成功!!

Python3 OS 文件/目錄方法 Python3 OS文件/目錄方法