如果我在Python 3中将文件截断为零,是否还需要寻找零位? [英] If I truncate a file to zero in Python 3 do I also need to seek to position zero?

查看:83
本文介绍了如果我在Python 3中将文件截断为零,是否还需要寻找零位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此问题的回答呼叫truncate实际上不会移动文件的位置.

According to the answers from this question calling truncate does not actually move the position of a file.

所以我的问题是,如果我truncate从文件中读取某些内容后长度为零的文件(因为我想从头开始写),是否还必须调用seek(0)以确保我在文件的开头吗?

So my question is, if I truncate a file to length zero after I read something from it (because I want to write from the beginning) should I / do I have to also call seek(0) to make sure I am at the beginning of the file?

这似乎有点多余,因为长度为零的文件必须位于右首?

This seems a little redundant because the file of length zero would have to be at the beginning right?

推荐答案

是的,您必须寻找位置0,截断不会更新文件指针:

Yes, you'll have to seek to position 0, truncating does not update the file pointer:

>>> with open('/tmp/test', 'w') as test:
...     test.write('hello!')
...     test.flush()
...     test.truncate(0)
...     test.tell()
... 
6
0
6

写入6个字节,然后截断为0仍将文件指针留在位置6.

Writing 6 bytes, then truncating to 0 still left the file pointer at position 6.

尝试向此类文件添加其他数据会在开始时导致NULL字节或垃圾数据:

Trying to add additional data to such a file results in NULL bytes or garbage data at the start:

>>> with open('/tmp/test', 'w') as test:
...     test.write('hello!')
...     test.flush()
...     test.truncate(0)
...     test.write('world')
...     test.tell()
... 
6
0
5
11
>>> with open('/tmp/test', 'r') as test:
...     print(repr(test.read()))
... 
'\x00\x00\x00\x00\x00\x00world'

这篇关于如果我在Python 3中将文件截断为零,是否还需要寻找零位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆