Amber.G
Amber.G

Reputation: 1513

Generate a text file with the name of current time in Python

I am using Python v2.x on Windows 8 bit-64.

The question is, I failed to generate a txt file named as real time.

Please see the code I have now:

import sys
import datetime

def write():

    # try:
        currentTime = str(datetime.datetime.now())
        print currentTime #output: 2016-02-16 16:25:02.992000
        file = open(("c:\\", currentTime, ".txt"),'a')   # Problem happens here
        print >>file, "test"
        file.close()

I tried different ways to modify the line file = open(("c:\....)) but failed to create a text file like 2016-02-16 16:25:02.992000.txt

Any advice please?

Upvotes: 2

Views: 1742

Answers (2)

Seekheart
Seekheart

Reputation: 1173

Here's a more efficient way to write your code.

import sys
import datetime

def write():
        currentTime = str(datetime.datetime.now())
        currentTime = currentTime.replace(':', '_')
        with open("c:\\{0}.txt".format(currentTime), 'a') as f:
             f.write("test")

Upvotes: -2

Robᵩ
Robᵩ

Reputation: 168646

In Windows, : is an illegal character in a file name. You can never create a file that has a name like 16:25:02.

Also, you are passing a tuple instead of a string to open.

Try this:

    currentTime = currentTime.replace(':', '_')
    file = open("c:\\" + currentTime + ".txt",'a')

Upvotes: 6

Related Questions