Best way to retrieve variable values from a text file?

后端 未结 10 2181
再見小時候
再見小時候 2020-11-30 19:44

Referring on this question, I have a similar -but not the same- problem..

On my way, I\'ll have some text file, structured like:

var_a: \'home\'
var_         


        
10条回答
  •  粉色の甜心
    2020-11-30 20:31

    If your data has a regular structure you can read a file in line by line and populate your favorite container. For example:

    Let's say your data has 3 variables: x, y, i.

    A file contains n of these data, each variable on its own line (3 lines per record). Here are two records:

    384
    198
    0
    255
    444
    2
    

    Here's how you read your file data into a list. (Reading from text, so cast accordingly.)

    data = []
    try:
        with open(dataFilename, "r") as file:
            # read data until end of file
            x = file.readline()
            while x != "":
                x = int(x.strip())    # remove \n, cast as int
    
                y = file.readline()
                y = int(y.strip())
    
                i = file.readline()
                i = int(i.strip())
    
                data.append([x,y,i])
    
                x = file.readline()
    
    except FileNotFoundError as e:
        print("File not found:", e)
    
    return(data)
    

提交回复
热议问题