file.truncate() 在文件 python 前留下白色 space

file.truncate() leaves white space in front of file python

当我使用 truncate() 时,它会在文件前面留下白色 space。这导致我有千兆字节的白色 space 需要加载到 ram

f = open("test.txt","r+")
for i in range(0,100):
    f.truncate(0)
    f.write("End of file")
f.close()

留下一个看起来像这样的文件

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             End of file

我该如何解决这个问题?

当您在每次迭代中使用 f.seek(0) 时,它的行为正确如下:

    f = open("test.txt","r+")
    for i in range(0,100):  
        f.seek(0)
        f.truncate(0)
        f.write("End of file")
    f.close()