Python: Open () using a variable
I am having a problem opening a file with a randomly generated name in Python 2.6.
import random
random = random.randint(1,10)
localfile = file("%s","wb") % random
Then I get an error on the last line:
TypeError: unsupported operand type(s) for %: 'file' and 'int'
I just can't figure it out myself, nor with Google, but in my opinion there must be a cure for this.
a source to share
This will probably work:
import random
num = random.randint(1, 10)
localfile = open("%d" % num, "wb")
Please note that I changed a couple of things here:
-
You should not assign the generated random number to a named variable
random
as you are overwriting an existing module referencerandom
. In other words, you will no longer be able to accessrandom.randint
if you overwrite with arandom
randomly generated number. -
The formatting operator (
%
) must be applied to the string you are formatting, not to a method callfile
. -
file
Deprecated in Python 3 I think . It's time to useopen
insteadfile
. -
Since you are formatting an integer to a string, you should write
"%d"
instead"%s"
(although the latter will work too).
An alternative recording method "%d" % num
is str(num)
, which may be slightly more efficient.
a source to share