如何读取文本文件并将其存储为python中的不同变量

时间:2018-11-02 16:40:29

标签: python python-3.x

我当前在文本文件中:

    tickets = []
    ticketPrice = 2.20
    ticketsNo =  150
    income = ticketPrice*ticketsNo
    ticketHi = 54
    limit = 1
    winners = []
    numbers = []
    winningTickets = []

我现在将如何读取文件并使其创建变量并相应地存储值?我知道

    with open("file.txt", "r") as f:
        //do stuff

但是我不知道如何以我追求的方式实现它。 预先感谢

1 个答案:

答案 0 :(得分:0)

使用assignment unpacking

with open("file.txt", "r") as f:
    data = f.readlines()


tickets, ticketPrice, ticketsNo, income, ticketHi, limit, winners, 
numbers, winningTickets = [d.split('=')[1].split('\n')[0] for d in data]

解压缩的结果将为string类型。对于int值,您将必须解析变量,例如。 int(limit)