Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading