문제

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?

도움이 되었습니까?

해결책

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()

다른 팁

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')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top