views:

59

answers:

2

Good day,

I've ran into a problem with opening a file with randomly generated name in Python 2.6.

import random

random = random.randint(1,10)

localfile = file("%s","wb") % random

Then I get an error message about the last line

TypeError: unsupported operand type(s) for %: 'file' and 'int' 

I just couldn't figure this out by myself nor with Google, but there has to be a cure for this, I believe.

Thanks.

+8  A: 

This will probably work:

import random

num = random.randint(1, 10)
localfile = open("%d" % num, "wb")

Note that I've changed a couple of things here:

  1. You shouldn't assign the generated random number to a variable named random as you are overwriting the existing reference to the module random. In other words, you will not be able to access random.randint any more if you overwrite random with the randomly generated number.

  2. The formatting operator (%) should be applied to the string you are formatting, not the call to the file method.

  3. I guess file is deprecated in Python 3. It's time to get used to using open instead of file.

  4. Since you are formatting an integer into a string, you should write "%d" instead of "%s" (although the latter would work as well).

An alternative way of writing "%d" % num is str(num), which might be a bit more efficient.

Tamás
Thank you! The "%d" % num method works fine.But I can't figure out how to use either str(num) or int(num) in the same case, it seems to be quite hard to move from PHP to Python.
You can use `str()` by doing `open(str(num), 'wb')`, `int()` won't work in this case since `open` expects the first parameter to be a `string`, also it` wouldn't do that much, since `num` is already an `integer`.
Ivo Wetzel
Must have been my mistake it didn't work last time, but thank you very much for your reply!
+2  A: 

Try:

localfile = file("%s" % random,"wb")
guillermooo
Thanks, that did the job!