Python: Open() using a variable
I've run into a problem when 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 message about the last line:
开发者_Go百科TypeError: unsupported operand type(s) for %: 'file' and 'int'
I just can't figure this out by myself, nor with Google, but there has to be a cure for this, I believe.
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:
You shouldn't assign the generated random number to a variable named
random
as you are overwriting the existing reference to the modulerandom
. In other words, you will not be able to accessrandom.randint
any more if you overwriterandom
with the randomly generated number.The formatting operator (
%
) should be applied to the string you are formatting, not the call to thefile
method.I guess
file
is deprecated in Python 3. It's time to get used to usingopen
instead offile
.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.
Try:
localfile = file("%s" % random,"wb")
精彩评论