简体   繁体   English

将变量名称分配给python中的不同文件

[英]Assign variable names to different files in python

I am trying to open various text files simulataneously in python. 我试图同时在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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM