Assume we have a text file named MyFile.txt
, which is structured like this:
some info
some more info
Unit: Unit1
E 32 5 5 ee
R 123 534 345 543 634 634 345
R 543 634 634 345 123 534 345
We want to store data from the lines that start with R
in a list called Data
(which will later be converted to a dataframe), and we want to add the "Unit name" ( Unit1
here) to the end of each line, so that the end result would look like this:
print(Data)
R 123 534 345 543 634 634 345 Unit1
R 543 634 634 345 123 534 345 Unit1
The following function fn
will loop through each line, store lines that start with R
in UN
, store the word Unit1
in a new list called UN
, and append it to the end of each line:
UN = []
Data = []
def fn(FileName):
with open(FileName, "r") as fi:
for line in fi:
if line.startswith("Unit"):
UN.append(line.split()[1])
elif line.startswith("R"):
Data.append(line.split()[0:] + list(UN))
In the event that our text file has two lines that start with Unit
:
some info
some more info
Unit: Unit1
E 32 5 5 ee
Unit: Unit1
R 123 534 345 543 634 634 345
R 543 634 634 345 123 534 345
The function above would append Unit1
to the end of each line twice, resulting in this:
R 123 534 345 543 634 634 345 Unit1 Unit1
R 543 634 634 345 123 534 345 Unit1 Unit1
How can we stop the loop after it finds the unit name one time, but continue with the rest of the loop so that it only appends the unit name once?
Is there a specific reason you are using list to store the unit? would both units be the same? in this case instead of storing the unit in a list you can simply store it in a variable, if your loop comes across it a second time it just overwrites the variable so you are still only appending one unit.
UN = ''
Data = []
def fn(FileName):
with open(FileName, "r") as fi:
for line in fi:
if line.startswith("Unit"):
UN = line.split()[1]
elif line.startswith("R"):
Data.append(line.split()[0:] + [UN])
if you want to make sure you only pick the first entry of unit you can add an additional if statement to check if 'UN' is empty or not.
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.