human_dictionary
human_dictionary

Reputation: 1

Open() in Python not working using a variable involving datetime.datetime.now() in the filename

I have a program which tries to use open() to name a file using a variable which contains datetime information. the code i have is:

now = datetime.datetime.now()
filename = ''.join(['log ', str(now), '.txt'])
log = open(filename, mode = 'a')

when I run this code, it gives this error:

line 58, in <module>
    log = open(filename, mode = 'a')
OSError: [Errno 22] Invalid argument: 'log 2014-02-07 21:02:16.475880.txt'

this code works if I replace open(filename) with a string, even with the string outputted by the error. I have also tried formatting filename as a string using the str() function, but that returns the same error.

Upvotes: 0

Views: 433

Answers (1)

Yam Mesicka
Yam Mesicka

Reputation: 6581

The : character is invalid on windows filesystem.

Also, consider converting the date to string using the strftime function, and not by using the str() function:

now = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')

Upvotes: 4

Related Questions