Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new line to head of log file using Python

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
like image 209
Federer Avatar asked Jan 24 '26 06:01

Federer


1 Answers

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 ?

like image 108
Cédric Julien Avatar answered Jan 25 '26 19:01

Cédric Julien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!