Skip to content Skip to sidebar Skip to footer

Python Loop Through A Text File Reading Data

I am new to python, and although I am sure this might be a trivial question, I have spent my day trying to solve this in different ways. I have a file containing data that looks l

Solution 1:

All lines are instances of str, so you break out on the first line. Remove that test, and test for an empty line by stripping away whitespace first:

def dat_fun():
    withopen("inpfile.txt", "r") as ifile:
        for line in ifile:
            ifnot line.strip():
                breakyield line

I don't think you need to break at an empty line, really; the for loop ends on its own at the end of the file.

If your lines contain other sorts of data, you'd need to do the conversion yourself, coming from string.

Solution 2:

With structured data like this, I'd suggest just reading what you need. For example:

withopen("inpfile.txt", "r") as ifile:
    first_string = ifile.readline().strip() # Is this the name of the data set?
    first_integer = int(ifile.readline()) # You haven't told us what this is, either
    n_one = int(ifile.readline())
    n_two = int(ifile.readline())

    x_vals = []
    y_vals = []
    z_vals = []

    for index inrange(n_one):
         x_vals.append(ifile.readline().strip())
    for index inrange(n_two):
         y_vals.append(ifile.readline().strip())
    for index inrange(n_one*n_two):
         z_vals.append(ifile.readline().strip())

You can turn this into a dataset generating function by adding a loop and yielding the values:

withopen("inpfile.txt", "r") as ifile:
    whileTrue:
        first_string = ifile.readline().strip() # Is this the name of the data set?if first_string == '':
            break
        first_integer = int(ifile.readline()) # You haven't told us what this is, either
        n_one = int(ifile.readline())
        n_two = int(ifile.readline())

        x_vals = []
        y_vals = []
        z_vals = []

        for index inrange(n_one):
            x_vals.append(ifile.readline().strip())
        for index inrange(n_two):
            y_vals.append(ifile.readline().strip())
        for index inrange(n_one*n_two):
            z_vals.append(ifile.readline().strip())
        yield (x_vals, y_vals, z_vals) # and the first string and integer if you need those

Solution 3:

defdat_fun():
    withopen("inpfile.txt", "r") as ifile:
        for line in ifile:
            ifisinstance('line', str) or (not line): # 'line' is always a str, and so is the line itselfbreakfor line in ifile:
                yield line

Change this to:

defdat_fun():
    withopen("inpfile.txt", "r") as ifile:
        for line in ifile:
            ifnot line:
                breakyield line

Post a Comment for "Python Loop Through A Text File Reading Data"