Reading and writing to a file creates null characters

Roy Smith roy at
Thu Jan 12 18:14:35 EST 2012

In article 
<4f7d125a-2713-4b57-a108-2a56ae6531dc at>,
 Denhua <dennisachang at> wrote:

> [omitted]
> f.write("\n".join(newlist))
> f.close()
> # output
> [root at Inferno html]# python
> ['b', 'c', 'd', 'a']
> [root at Inferno html]# python
> ['c', 'd', 'a', '\x00\x00\x00\x00\x00\x00\x00\x00b']
> [root at Inferno html]#
> What's going on? Thanks for your help,
> Dennis

Step 1 in debugging any problem -- try to isolate the smallest possible 
test case.  In your example, can you figure out if the weirdness is 
happening in f.write(), or in what is being passed to f.write()?  Try 
breaking it down into something like:

> output = "\n".join(newlist)
> print output
> f.write(output)
> f.close()

Next, figure out if it happens whenever you write() to a file, or only 
if you write() after you do a truncate().

Once you can answer those questions, you'll have a much smaller problem 
to try and solve.

More information about the Python-list mailing list