Saphire
Saphire

Reputation: 1930

Python can't overwrite file

I am reading from a file, adding a line to it and then saving it back. In C# this would work - But not in Python. Can anyone tell me why?

f = "blogs/%s.comment" % blogtitle
if os.path.isfile(f):
    temp = file(f).readlines()
    temp.append(comment)

    overr = open(f, "w") #line 13
    for l in temp: overr.write(l)

The error I get is IOError: [Errno 13] Permission denied at line 13

I am running this file as a .wsgi in Apache and have 775 permissions in the folder where the file is stored.

Upvotes: 0

Views: 2412

Answers (2)

user2357112
user2357112

Reputation: 280207

You didn't close the file. You should open the file in a with statement to handle closing. Also, it's simpler and more efficient to just open the file in append mode instead of reading the whole thing and writing it back:

path = "blogs/%s.comment" % blogtitle
with open(path, 'a') as f:
    f.write(comment)

Upvotes: 0

sshashank124
sshashank124

Reputation: 32189

You forgot to close the file after you had opened it the first time, do it as follows:

f = "blogs/%s.comment" % blogtitle
if os.path.isfile(f):
    with open(f, 'r') as fl:
        temp = fl.readlines()
        temp.append(comment)

    with open(f, "w") as fl:
        for l in temp: fl.write(l)

Upvotes: 1

Related Questions