lundi 3 mai 2021

Stopping a loop once it evaluates to true in python

Assume a text file named "File1.txt" has the following structure:

random information
data #29, 45392 records
Unit: Unit1  Location: AA11
2011-09-20 14:06:20.78 28 finished
more random info
2017-04-19 09:11:59.00 00:01:02.30 A24    8     7
2017-04-19 09:12:02.25 00:00:01.00 A22    3     3

We want to collect the name of the unit from this data (which is Unit1 in this case, as seen on the 3rd line of the file), so that we can refer to its value and store it in a dataframe. We can accomplish that with the following code:

un = [] #to store unit name
with open("File1.txt","r") as fi:
    for line in fi:
        if line.startswith("Unit"):
            un.append(line.split()[1])
# we could then create a dataframe and populate it with the value of un as needed

Now what if the text file (from the same "unit") has more than one line that starts with Unit:

random information
data #29, 45392 records
Unit: Unit1  Location: AA11
2011-09-20 14:06:20.78 28 finished
more random info
2017-04-19 09:11:59.00 00:01:02.30 A24    8     7
2017-04-19 09:12:02.25 00:00:01.00 A22    3     3
Unit: Unit1  Location: AA11

Both lines that start with Unit contain the same information (i.e., the name of our unit: Unit1), so we only need to collect the name one time. In this case, using the script above would result in a list with two elements (Unit1 would be repeated twice). How can we essentially tell the loop to stop once it evaluates to true?

Aucun commentaire:

Enregistrer un commentaire