简体   繁体   中英

How to read a text file and store as different variables in python

Inside the text file I currently have:

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

How would I now read the file and have it create variables and store values accordingly? I know about

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

but I don't know how to implement it in the fashion I'm after. Thanks in advance

Using 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]

The result of this unpacking will be of type string . For int values, you will have to parse the variable eg. int(limit) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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