Python3 File truncate() 方法
概述
truncate()方法用於截斷文件,如果指定了可選參數size,則表示截斷文件為size個字符。如果沒有指定size,則重置到當前位置。
語法
truncate() 方法語法如下:
fileObject.truncate( [ size ])
參數
size --可選,如果存在則文件截斷為size字節。
返回值
該方法沒有返回值。
實例
以下實例演示了truncate() 方法的使用:
文件w3big.txt 的內容如下:
1:www.w3big.com 2:www.w3big.com 3:www.w3big.com 4:www.w3big.com 5:www.w3big.com
循環讀取文件的內容:
#!/usr/bin/python3 fo = open("w3big.txt", "r+") print ("文件名: ", fo.name) line = fo.readline() print ("读取行: %s" % (line)) fo.truncate() line = fo.readlines() print ("读取行: %s" % (line)) # 关闭文件 fo.close()
以上實例輸出結果為:
文件名: w3big.txt 读取行: 1:www.w3big.com 读取行: ['2:www.w3big.com\n', '3:www.w3big.com\n', '4:www.w3big.com\n', '5:www.w3big.com\n']
以下實例截取w3big.txt 文件的10個字節:
#!/usr/bin/python3 # 打开文件 fo = open("w3big.txt", "r+") print ("文件名为: ", fo.name) # 截取10个字节 fo.truncate(10) str = fo.read() print ("读取数据: %s" % (str)) # 关闭文件 fo.close()
以上實例輸出結果為:
文件名为: w3big.txt 读取数据: 1:www.runo