根据这个问题的答案,调用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)
| 归档时间: |
|
| 查看次数: |
1217 次 |
| 最近记录: |