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.

+2


a source to share


2 answers


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 reference random

    . In other words, you will no longer be able to access random.randint

    if you overwrite with a random

    randomly generated number.

  • The formatting operator ( %

    ) must be applied to the string you are formatting, not to a method call file

    .

  • file

    Deprecated in Python 3 I think . It's time to use open

    instead file

    .

  • 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.

+9


a source


Try:



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

      

+3


a source







All Articles