Python 文件 truncate() 方法

实例

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

  1. f = open("demofile2.txt", "a")
  2. f.truncate(20)
  3. f.close()
  4.  
  5. #open and read the file after the truncate:
  6. f = open("demofile2.txt", "r")
  7. print(f.read())

定义和用法

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

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

语法

  1. file.truncate(size)

参数值

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