Hi,

I am new user of python and now i am struck with a problem. Please help me in solving this.

I am trying to create a logfile for every action by using a standard template available.
My code is able to create & rename a log file by using template provided.But it is not able to write any thing is the excel.

Please help me out in knowing what would be the problem.

Below is my code.

import shutil,time,datetime
now = datetime.datetime.now()
strtime1=str(time.localtime()[3])+str(time.localtime()[4])+str(time.localtime()[5])
newfile="C:/"+"Resultlog"+str(strtime1)+".xls"
shutil.copyfile("C:/Template.xls",newfile)
tempname=open(newfile,"a")
tempname.write("starting Execution\n")
print "able to write inthe new file"
tempname.close()

I'm afraid this is not going to work this way. You now open the file as if it is a plain text file and write to it. As a matter of fact when you open your resulting log in notepad, you will probably see a lot of weird characters and a little line at the end saying 'starting Execution'. Excel uses a specific file format which you can't write to this way, it will just ignore this line or not open at all.

There are a few things you could try: You could try to figure out which format Excel uses. This might not be possible because Excel is not an open source program. I'm sure that you would be able to write to excel somehow using python or a combination of this and visual basic, but I wouldn't go there for now.

A more reasonable option would be to use a plain text file to write to. I don't know what this template of yours should be doing, so of course it depends on this as well.

An even more elegant solution would be to uses pythons own logging routines. http://docs.python.org/library/logging.html gives an introduction, but google will also help. Here you can have a config file that formats your logging and might do what you want to do in your template.

Hope this helps.

Thanks for the link.

I will try to create my logfile by using the link provided.

But still i wonder why my code is not working.
because it works fine,if i comment 5th line of my code.
(i.e with out using the any template)

When you're not using the template, it actually creates a simple textfile which happens to have a .xls extension. You should try to open both created files (with or without template) in notepad and you'll see the difference. Excel is able to read in text files, so that's why you are able to open it in excel.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.