Python 文件 truncate() 方法

实例

以 "a" 打开文件进行追加,然后将文件截断为 20 个字节:

f = open("demofile2.txt", "a")
f.truncate(20)
f.close()

#open and read the file after the truncate:
f = open("demofile2.txt", "r")
print(f.read())

运行实例

定义和用法

truncate() 方法将文件大小调整为给定的字节数。

如果未指定大小,将使用当前位置。

语法

file.truncate(size)

参数值

参数 描述
size 可选。截断后文件的大小(以字节计)。默认值:None,表示当前文件流位置。