pythontruncateinvalid-characters

invalid characters happens by using truncate(0) in python


I used truncate(0) in python to overwrite data on my file. Part of the code is like this:

l=f.readlines()
f.truncate(0)
    for w in l:
        data=w.split()
        if 105==int(data[0]): 
            f.write('%s %s\n'%((str(data[0]),str(np.mean(b)))))
        else:
            f.write('%s %s\n'%((str(data[0]),(data[1]))))

The code works fine and output is correct, but when I open the output file (which is in txt format) I got "invalid characters" errors. At the head of the output file, I have this extra data:

\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00

And the bad character error is for these extra data. After this invalid-characters, I have the data of output, made by python, which is correct.

Why does this happen, and how can I fix it?


Solution

  • Because after the f.readlines() call, the file position is still set to the original end of file. truncate doesn't change the file position, so when you write your string, it pads out to the old end of file with zeros. Just do f.seek(0) before you truncate.