这与此question here关联,我使用了第一个答案,我尝试更改代码,但是由于该示例在变量中包含“ []”,因此它似乎不起作用
我在这里有一个文本文件:
room1North = CP
room1East = CP
room1South = OP
room1West = OP
room2North = OP
room2East = CP
room2South = EP
room2West = OP
我希望Python使用文本文件中的值创建变量,以便Python中的变量“ room1North = CP”
到目前为止,我有以下代码
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in data]
我收到以下错误:
IndexError: list index out of range
答案 0 :(得分:3)
您实际上并不需要单独的变量;您需要一个dict
,其键是从文件中读取的。
with open("maze files.txt", "r") as f:
data = {k:v for k, v in [line.strip().replace(' ', '').split("=") for line in f]}
# data["room1North"] == "CP"
# data["room1East"] == "CP"
# data["room1South"] == "OP"
# etc
答案 1 :(得分:0)
我认为使用字典而不是单纯依靠变量会更幸运。
with open("maze files.txt", "r") as f:
data = f.readlines()
rooms = {}
for i in data:
currentRoom = i.replace(' ', '').strip().split('=')
rooms[currentRoom[0]] = currentRoom[1]
剩下的就是像下面这样的字典
print(rooms)
#{'room1North ': ' CP', 'room1East ': ' CP', 'room1South ': ' OP', 'room1West ': ' OP', 'room2North ': ' OP', 'room2East ': ' CP', 'room2South ': ' EP', 'room2 West ': ' OP'}
您可以通过rooms["room1North"]
答案 2 :(得分:0)
将您的代码更改为波纹管
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in ''.join(data).split('\n')]