开发者

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.开发者_Go百科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.


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


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜