2

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?

Alberto Bonsanto
  • 17,556
  • 10
  • 64
  • 93
Amber.G
  • 1,343
  • 5
  • 12
  • 16

2 Answers2

6

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')
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Thx Rob, It works! :) One more question, I tried to replace : to \, but failed with IOError " No such file or directory". Does it mean ":" cannot be replaced by "/" ? – Amber.G Feb 17 '16 at 00:58
  • Hi @Amber.G. You can click the check mark to the left of Rob's response to confirm that Rob's response answers your question. – wrkyle Feb 17 '16 at 03:17
  • @Amber.G \ is the escape character in python so you would need to use "\\"; and anyway both \ and / indicate a directory for Windows so cannot be used as part of the file name. Pick some other character or just remove the : altogether. See http://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names – Stuart Feb 17 '16 at 13:05
  • Thank you very much, @Rob. Your answer is accepted and up. :) – Amber.G Feb 17 '16 at 18:39
-2

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")
Seekheart
  • 1,135
  • 7
  • 8