如果我在Python 3中将文件截断为零,我是否还需要寻找零位?

Sta*_*tec 6 python file-io

根据这个问题的答案,调用truncate实际上并没有移动文件的位置.

所以我的问题是,如果我从truncate一个文件读取长度为零(因为我想从头开始写),我是否应该调用seek(0)以确保我在文件的开头?

这似乎有点多余,因为长度为零的文件必须在开头呢?

Mar*_*ers 10

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

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

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

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

>>> 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'
Run Code Online (Sandbox Code Playgroud)