Reading and writing to a file creates null characters

MRAB python at mrabarnett.plus.com
Thu Jan 12 18:21:07 EST 2012


On 12/01/2012 22:26, Denhua wrote:
> 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,
 >
I think this is the relevant part of the documentation:

"""The current file position is not changed. Note that if a specified 
size exceeds the file’s current size, the result is platform-dependent: 
possibilities include that the file may remain unchanged, increase to 
the specified size as if zero-filled, or increase to the specified size 
with undefined new content.
"""

In other words, you also need to reset the file pointer to the start of
the file.



More information about the Python-list mailing list