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 篇原创文章 · 获赞 3 · 访问量 768

猜你喜欢

转载自blog.csdn.net/weixin_39630484/article/details/86032024