Reading and writing to a file creates null characters

Denhua dennisachang at gmail.com
Thu Jan 12 17:26:40 EST 2012


Hi,

I've got a file which I'd like to read, modify and write.

# file contents
a
b
c
d

My script reads the file contents into a list and rotates the list and
writes it back to the same file.
Problem is that the output contains null characters. I don't know
where they are coming from.

#!/usr/bin/env python

def rotate(l):
        return l[1:] + [l[0]]


f = open("/tmp/.rrd", 'r+')

lines = [ line.strip() for line in f.readlines() ]


newlist = rotate(lines)

print newlist
f.truncate(0)

f.write("\n".join(newlist))
f.close()

# output

[root at Inferno html]# python rotate.py
['b', 'c', 'd', 'a']
[root at Inferno html]# python rotate.py
['c', 'd', 'a', '\x00\x00\x00\x00\x00\x00\x00\x00b']
[root at Inferno html]#


What's going on? Thanks for your help,
Dennis



More information about the Python-list mailing list