python 3 . 6 怪异的truncate函数

python3.6 文件操作函数 truncate 坑


官网上对文件截取函数的解释是这样的:

truncate(size=None)
Resize the stream to the given size in bytes (or the current position
if size is not specified).  The current stream position isn’t changed.
This resizing can extend or reduce the current file size.  In case of
extension, the contents of the new file area depend on the platform
(on most systems, additional bytes are zero-filled).  The new file size is returned.

根据上述文档说明不带参truncate()函数会截取文件头到当前游标位置的字节。
但是,当文件以文本的形式打开时,进行读操作造成游标改变时,文件不会被截取:

with open('test','w',encoding='utf-8') as f:
    f.write('我高兴\n'*5)

with open('test','r+',encoding='utf-8') as f:
    print(f.read(5))
    print(f'当前指针位置{f.tell()}')
    f.truncate()

with open('test','r',encoding = 'utf-8') as f:
    print(f.read())
我高兴
我
当前指针位置14
我高兴
我高兴
我高兴
我高兴
我高兴

同样的操作,当文件以二进制方式打开时,文件才会被截取:

with open('test','w',encoding='utf-8') as f:
    f.write('我高兴\n'*5)

with open('test','r+b') as f:
    print(f.read(14))
    print(f'当前指针位置{f.tell()}')
    f.truncate()

with open('test','r',encoding = 'utf-8') as f:
    print(f.read())
b'\xe6\x88\x91\xe9\xab\x98\xe5\x85\xb4\r\n\xe6\x88\x91'
当前指针位置14
我高兴
我

大胆猜测:以文本方式打开的文件流同时存在两个游标,而trunkcate调用的游标在文件读过程中不会改变

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值