File IO Issues, help :(

Peter Otten __peter__ at web.de
Tue Apr 29 02:35:46 EDT 2008


Kevin K wrote:

> On Apr 29, 12:55 am, Peter Otten <__pete... at web.de> wrote:
>> Kevin K wrote:
>> > On Apr 29, 12:38 am, "Eric Wertman" <ewert... at gmail.com> wrote:
>> >> chuck in a jsfile.close().  The buffer isn't flushing with what you
>> >> are doing now.  jsfile.flush() might work... not sure.  Closing and
>> >> re-opening the file for sure will help though.
>>
>> > Yeah sorry I forgot to include the close() in the quote but its there.
>> > In fact I moved it up a bit and still no luck heres the new code:
>>
>> > jsfile = open("../timeline.js", "r+")
>> > jscontent = jsfile.readlines()
>> > jsfile.truncate()
>>
>> > for line in jscontent:
>> > if re.search('var d =', line):
>> > line = "var d = \""+mint['1'].ascdate()+"\"\n"
>> > print line
>> > jsfile.write(line)
>> > jsfile.close()
>>
>> > I tried this can got the same result...??
>>
>> """
>> truncate(...)
>>     truncate([size]) -> None.  Truncate the file to at most size bytes.
>>
>>     Size defaults to the current file position, as returned by tell().
>> """
>>
>> After the readlines() call the current file position is at the end of the
>> file. Try jsfile.truncate(0).
>>
>> Also note that readlines() reads the whole file into memory. For large
>> files it would therefore be better to write to a new file and rename it
>> afterwards.
>>
>> Peter
> 
> Thanks Peter that seemed to be most of the problem, however I now have
> a bunch of null characters in the file. Could it be an unwanted line
> in the list that im writing?

Oops, truncate() doesn't affect the file position. You probably need

jsfile.truncate(0)
jsfile.seek(0)

Peter



More information about the Python-list mailing list