九零不老心
发布于 2020-09-29 / 3 阅读 / 0 评论 / 0 点赞

cannot truncate a file that has been open in write-only mode

python代码:
#!/usr/bin/env python3
# encoding=utf-8

import time
import os

with open('test.txt', "w") as file:
    count = 0
    while True:
        count = count + 1
        # file.seek(0, os.SEEK_END)
        file.write("A append {}\n".format(count))
        file.flush()
        time.sleep(0.1)
执行该脚本不断输出内容到test.txt文件中,
然后开另一个窗口shell,执行: > test.txt置空日志文件,
发现日志文件头部变为空,后面的日志继续尾部增加,该日志文件ls -lh的大小并没有减少,
参考帖子,https://unix.stackexchange.com/questions/122929/emptying-a-file-without-disrupting-the-pipe-writing-to-it
得出结论:
That means you cannot truncate a file that has been open in write-only mode (and that's the same for read+write) as if you do, processes that had file descriptors open on the file, will leave NUL characters at the beginning of the file (those, except on OS/X, usually don't take space on disk though, they become sparse files).
Instead (and you'll notice most applications do that when they write to log files), you should open the file in append mode