Home > Back-end >  get a integer from a file in python
get a integer from a file in python

Time:10-22

I'm learning python, and I have a simple question. I have a file, and I need to read it, the file contains a header, and its divided by the size of the structures in the file, and the top of the pile, like this:

size=86 top=-1

so far, I only read the line, and it's working

def readinput(input):
    line = []
    line = input1.readline()
    
    print(line)
    

with open(sys.argv[1],'r') as input1:
    readinput(input1)

That's it, can you help me to get the size and the top in the header?

CodePudding user response:

You can parse it using a regex but I would just do something like this:

header = open(file_path,"r").readlines()[0] # read header line
kv = [kv.split("=") for kv in header.split(" ")] # iterate key=value pairs


for key,value in kv:
    print(f"{key}={value}")

# size=96
# top=1

CodePudding user response:

A bit more information on your specific use case would be helpful (assuming that you want to define two variables, where size=86 and top=-1), but in the meantime, you could try something like this:

#helper method to parse input
def readinput(input):
    #Read the input file
    line = input.readline()
    #Split the top line at the space value
    stringSplit = line.split(" ")
    #Then, parse the size value
    sizeValue = stringSplit[0].split("=")[1]
    #Then parse the top value
    topValue = stringSplit[1].split("=")[1]
    #set the two values in a dictionary
    output = {"size": sizeValue,
            "top": topValue}
    #print the output for a preview
    print(output)
    #return the output values to use elsewhere
    return output

with open(sys.argv[1],'r') as input1:
    results = readinput(input1)
    #size value referenced here
    sValue = results["size"]
    #top value referenced here
    tValue = results["top"]

The code is pretty heavily commented, but may help in getting started

  • Related