0

I'm pretty new to python, and am wondering if there's any way to put a variable into a file name, so that you can create files with different names each time.

In my particular case, I'd like to add date and time to the file name. If it was possible, this would work perfectly:

example = open("Path/to/file%s", "w") % str(datetime.now())

...but it doesn't. Is there any way to get that sort of functionality using a different approach? I've tried searching for an answer either way using multiple phrasings, but I can't find a yea or nay on it.

Thanks in advance guys.

EDIT: That was supposed to be an open() function, adjusted accordingly.

1
  • 1
    Your way would work, but you would move the tuple next to the path, like example = ("Path/to/file%s" % str(datetime.now()), "w") Commented Sep 11, 2012 at 3:13

4 Answers 4

4

This should work. format() will replace the placeholder {0} in the string with the formatted datetime string (datestr).

>>> from datetime import datetime
>>> datestr = datetime.strftime(datetime.today(), "%Hh %Mm %Ss %A, %B %Y")
>>> examplefile = open("/home/michael/file{0}".format(datestr), 'w')
>>> print(examplefile)
<open file '/home/michael/file21h 20m 34s Monday, September 2012', mode 'w' at 0x89fcf98>
Sign up to request clarification or add additional context in comments.

5 Comments

Great answer; unfortunately I goofed and wrote it like I was making a tuple. It doesn't look like this works for making a file, I'm getting the "invalid mode or filename" exception.
@Daniel I'm not sure what you mean "wrote it like I was making a tuple". I've update the answer with a working example. Hope that helps. :)
Ah, it's the colons. Is there a way to get the date in a different format, or do I need to manually edit them out? For instance, I'm now looking at something more like:
date = str(datetime.now()) date = date[:19] ...to trim the end off. I'm assuming I now need to make a for loop to replace the colons with periods (meant to just edit previous comment, accidentally hit enter instead of shift+enter '^^)
datetime.strftime(datetime.today(), "%Hh %Mm %Ss %A, %B %Y") might be what you're looking for. It gives an output like this '21h 14m 27s Monday, September 2012'. Alternatively you can specify whatever format you particularly feel like. The page for the formatters is here.
1

Modifying your answer to still use the old-style % formatting, you might do:

example = open("Path/to/file%s" % datetime.now(), "w")

Note that I've called open(), which is probably what you want to do (otherwise you're just creating a tuple). Also, using the %s format specifier automatically converts the argument to a string, so you don't really need the str().

Comments

1

The reason your example doesn't work has nothing to do with files.

example = ("Path/to/file%s", "w") % str(datetime.now())

The above is using the % operator with a tuple on the left, and a string on the right. But the % operator is for building strings based on a string template, which appears on the left of the %. Putting a tuple on the left just doesn't make sense.

You need to break what you want to do into more basic steps. You start with "I want to open a file whose name includes the current date and time". There is no way to directly do that, which is why you couldn't find anything about it. But a filename is just a string, so you can use string operations to build a string, and then open that string. So your problem isn't really "how do I open a file with the date/time in the name?", but rather "how do I put the date/time into a string along with some other information?". You appear to already know an answer to that question: use % formatting.

This makes sense; otherwise we'd have to implement every possible string operation for files as well as for strings. And also for everything else we use strings for. That's not the way (sane) programming works; we want to be able to reuse operations that already exist, not start from scratch every time.

So what you do is use string operations (that have nothing to do with files, and neither know nor care that you're going to eventually use this string to open a file) to build your filename. Then you pass that string to the file opening function open (along with the "w" string to specify that you want it writeable).

For example:

filename = "Path/to/file%s" % datetime.now()
example = open(filename, "w")

You can put it in one line if you want:

example = open("Path/to/file%s" % datetime.now(), "w")

But if you're relatively new to programming and to Python, I recommend you keep your small steps broken out until you're more comfortable with things in general.

2 Comments

I do have some previous experience with Java, but it's true that I have a tendency to jump into things way over my head. =D I'll try to take your advice to heart.
@Daniel: Jumping in is great! It's how you learn. But almost always when you have a problem figuring out how to do something and nothing seems to exist that does what you need, it's that way because "the way" to do what you need is to build it out of more basic operations, for which there are ready made pieces.
0

All the answers posted here identify the problem correctly, that is your string formatting is not correct.

You should also check that the string you end up with is actually a valid file name for the operating system you are trying to create files on.

Your example doesn't generate a valid file name on Windows, and although will work on Linux, the file name created will not be what you expect:

>>> f = open(str(datetime.datetime.now()),'w')
>>> f.write('hello\n')
>>> f.close()
>>> quit()

-rw-r--r-- 1 burhan burhan 6 Sep 11 06:53 2012-09-11 06:53:04.685335

On Windows it doesn't work at all:

>>> open(str(datetime.datetime.now()),'w')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('w') or filename: '2012-09-11 06:51:26.873000'

This would be a better option (2.6+):

filename = "Path/to/file/{0.year}{0.month}{0.day}".format(datetime.now())

For older versions of Python, you can use the classic option:

filename = "Path/to/file/%s" % datetime.strftime(datetime.now(),"%Y%m%d")

1 Comment

You're right; the problem was worsened by the datetime.now() formatting having colons, so I couldn't create a file with that in the name. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.