you always have to have the namespace declared before assignment, either on a previous line or on the left of a statement. Anyway you can do:
files = {f:open("DOS%s" % f) for f in [1,2,11]}
then access files like:
files[1].read()
Pergunta
I am trying to open various text files simulataneously in python. I want to assign a unique name to each file. I have tried the follwoing but it is not working:
for a in [1,2,11]:
"DOS%s"%a=open("DOS%s"%a,"r")
Instead I get this error:
SyntaxError: can't assign to operator
What is the correct way to do this?
Solução
you always have to have the namespace declared before assignment, either on a previous line or on the left of a statement. Anyway you can do:
files = {f:open("DOS%s" % f) for f in [1,2,11]}
then access files like:
files[1].read()
Outras dicas
Use a dict :
files = {}
for a in [1,2,11]:
files["DOS%s"%a] = open("DOS%s"%a,"r")
You get an error because you're trying to assign a value to something that is not a variable. This is pretty basic stuff, so I'd suggest that you do some sort of introductory programming course.
When you need a string as a lookup key, a dictionary is your friend:
files = {}
for a in [1, 2, 11]:
filename = 'DOS%s' % a
files[filename] = open(filename, 'r')