开发者

Python: Open() using a variable

开发者 https://www.devze.com 2022-12-29 18:34 出处:网络
I\'ve run into a problem when opening a file with a randomly generated name in Python 2.6. import random

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:

  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.


Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消