Reputation: 620
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
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
Reputation: 1989
You must open it using 'r' flag, for reading.
open('/home/me/dev/Django/rulebase/result.rb', 'r')
Upvotes: 0