我当前在文本文件中:
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
但是我不知道如何以我追求的方式实现它。 预先感谢
答案 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)
。