Python3读取文件并分配输出

时间:2018-10-24 17:27:13

标签: python

我有包含此值的test.txt文件,

11a,22a,33a,44a
11b,22b,33b,44b

如何读取输出并将其分配给变量,就像这样

a1 = 11a
a2 = 22a
a3 = 33a

非常感谢

2 个答案:

答案 0 :(得分:0)

尝试类似的方法以开始使用

with open("test.txt") as f:
    first_line = f.readline().split(",")
    a1 = first_line[0]
    a2 = first_line[1]
    a3 = first_line[2]

答案 1 :(得分:0)

可以在此处使用词典,以避免手动创建所有变量名

with open('test.txt') as f:
    content =  [line.strip() for line in f]

content = [j for i in content for j in i.split(',')]
dct = {i[::-1][:2]: i for i in content}

print(dct)
# {'a1': '11a', 'a2': '22a', 'a3': '33a', 'a4': '44a', 'b1': '11b', 'b2': '22b', 'b3': '33b', 'b4': '44b'}