am writing this algorithm that takes strings from a text file and appends them to an array. if the strings are in continuous line ex.
ABCD
EFG
HIJK
LMNOP
then they would be appended into the same array until it reaches a blank line at which point it stops and starts appending the next number of continuous arrays to a different array.
In my head a for loop is the way to go as i have the number of lines but i am just not sure how to check if a line has ANY TYPE of text or not (Not looking for any substrings just checking if the line itself contains anything).
CodePudding user response:
Simply check if the current line equal the new line character.
with open('filename.txt', 'r') as f:
for line in f:
if line == '\n':
print('Empty line')
else:
print('line contain string')
CodePudding user response:
If you're stripping the linebreak off each line, you can just check afterward to see if the result is empty. Given the following file text.txt
:
ABCD
EFG
HIJK
LMNOP
QRSTUV
WXYZ
here's an example of reading it into a list of lists of strings:
>>> arr = [[]]
>>> with open("text.txt") as f:
... for line in f:
... line = line.strip()
... if line:
... arr[-1].append(line)
... else:
... arr.append([])
...
>>> arr
[['ABCD', 'EFG', 'HIJK', 'LMNOP'], ['QRSTUV', 'WXYZ']]