Red
Red

Reputation: 1519

Writing empty string to textfile in Python

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.

Upvotes: 2

Views: 3935

Answers (3)

ars
ars

Reputation: 123488

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

f.truncate(0)
f.close()

Upvotes: 2

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

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()

Upvotes: 3

poke
poke

Reputation: 387577

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

Upvotes: 2

Related Questions