Reading and writing to a file creates null characters

Denhua dennisachang at gmail.com
Fri Jan 13 10:05:20 EST 2012


On Jan 12, 6:21 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:
> 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.

Great!
I added the line:
f.seek(0)
and that solved the problem.
Thanks to both of you for your help.
Dennis
P.s. I made assumptions about the truncate function.
I assumed that since the truncate function was clearing the file
therefore I assumed with nothing in the file that the file pointer
would be at the first position.


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



More information about the Python-list mailing list