Daniel
Daniel

Reputation: 3

Using variables in creating a file name

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.

Upvotes: 0

Views: 7735

Answers (4)

user849425
user849425

Reputation:

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>

Upvotes: 4

Burhan Khalid
Burhan Khalid

Reputation: 174624

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")

Upvotes: 0

Ben
Ben

Reputation: 71400

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.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 992907

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().

Upvotes: 1

Related Questions