2

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.

3 Answers 3

3

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I've updated the script and used ars's answer, but yours is correct in presented case. Thanks!
2

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

Comments

2

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

f.truncate(0)
f.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.