saiyan101
saiyan101

Reputation: 620

Django project not writing to file

Am trying to append a file in Django to do a string replace for some reason its not writing to the file. Am having no problems reading.

views.py

with open('/home/me/dev/Django/rulebase/result.rb', 'a') as discover_reading:
    mydiscover = File(discover_reading)
    for line in mydiscover:
        line.replace('input = "', 'this')
    mydiscover.closed

I get this error on my browser:

Exception Type:     IOError
Exception Value:    

File not open for reading

Upvotes: 0

Views: 198

Answers (2)

msvalkon
msvalkon

Reputation: 12077

The following will replace the contents of the file:

with open('/home/me/dev/Django/rulebase/result.rb', 'r') as discover_reading:
    lines = [line.replace('input = "', 'this') for line in discover_reading.readlines()]

with open('/home/me/dev/Django/rulebase/result.rb', 'w') as discover_reading:
    discover_reading.writelines(lines)

You're example does not work at all.

Read the docs for file objects and string.replace please. File is not a builtin function, str.replace does not replace in-place (strings are immutable) and the mydiscover.closed is for telling whether or not the file is closed, not for closing an open file.

Your original error was raised because you are attempting to read lines from a file you've opened with the a flag which stands for append.

Upvotes: 1

caio
caio

Reputation: 1989

You must open it using 'r' flag, for reading.

open('/home/me/dev/Django/rulebase/result.rb', 'r')

Upvotes: 0

Related Questions