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,表示當前文件流位置。 |