Reputation: 34795
I'm trying to add a new line in front of a date stamp in a log file. I have the following parts.
Open log file:
f = open("C:\Users\user\Desktop\Log.file")
Add a new line in front of the date "25/01/2012" (uniquely identifies each log line).
f.write("\n" + "25/01/2012")
Error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
f.write('\n' + "25/01/2012")
IOError: File not open for writing
Upvotes: 2
Views: 1417
Reputation: 6246
You need f = open("C:\Users\user\Desktop\Log.file", "w")
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files
Hope this helps.
Upvotes: 0
Reputation: 38147
f = open("C:\Users\user\Desktop\Log.file","w");
by default 'r' is assumed ie reading docs here
Note: 'w' will overwrite the existing file. Use 'a' to append
Upvotes: 2
Reputation: 80811
As shown in the python documentation for open(), the default mode is 'r' for reading, not for 'w' for writing. Try to use :
f = open("C:\Users\user\Desktop\Log.file", 'a')
to open your log file for writing (and not erasing it if it already exists)
Concerning your final goal, that is logging in files, did you have a look to the logging module which will allow you to format all your log record with date, level, PID and many usefull things ?
Upvotes: 6
Reputation:
open("C:\Users\user\Desktop\Log.file", "w")
But please take a look at http://docs.python.org/library/logging.html for logging with Python.
Edit: Even better: http://docs.python.org/howto/logging.html#logging-basic-tutorial
Upvotes: 1