tags:

views:

49

answers:

3

Quite embarassing issue, though i come from web development and rarely have to deal with files i/o.

I wrote a simple config updater for use on my shared hosting. It scans the directory for subdirectories, and then writes config lines to a file - one line for each subdirectory. The problem is, when it detects there are config lines but no subdirectories, it's supposed to leave config empty - which doesn't work! Coming here with this because docs aren't mention it and google isn't helpful either. Its Python 2.6.6 on Debian Lenny.

file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
    config = ''
file.write(config)
file.close()

In this case, file isn't changed at all. The funny thing is, making it forget config and just do file.write('') doesn't empty the file either, but puts \n in seemingly random positon of the line.

+1  A: 

You might want to use the 'w+' mode in the open call, to truncate the file.

poke
+2  A: 

You're using the r+ read-write mode. All reads and all writes update the file's position.

Try:

file = open('path', 'r+')
config = file.read()
## all the code inbetween works fine
## config is .split()-ed, hence the list
if config == ['']:
    config = ''
file.seek(0)    # rewind the file
file.write(config)
file.close()
Frédéric Hamidi
I've updated the script and used ars's answer, but yours is correct in presented case. Thanks!
Red
+2  A: 

If you're trying to empty the file, use truncate:

f.truncate(0)
f.close()
ars