0

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?

1
  • 1
    You're misusing the word simultaneously Commented May 15, 2014 at 12:25

3 Answers 3

3

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()
Sign up to request clarification or add additional context in comments.

Comments

2

Use a dict :

files = {}
for a in [1,2,11]:
    files["DOS%s"%a] = open("DOS%s"%a,"r")

Comments

0

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

4 Comments

a shorter way dosfiles = {"DOS%s"%a: open("DOS%s"%a,"r") for a in [1,2,11]}
@comiventor A lot less readable in my opinion. Newlines are not your enemy :)
surely not @Henrik :) I wanted to break the dictionary comprehension into two lines but pressing enter in comment just posts it instead of newline.
Come to think of it, it's not a bad idea to do this in a comprehension, but the double formatting string bugs me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.