user2251144
user2251144

Reputation: 31

If line not present in the text file - python

I have a list with a set of strings and another dynamic list:

arr = ['sample1','sample2','sample3']
applist=[]

I am reading a text file line by line, and if a line starts with any of the strings in arr, then I append it to applist, as follows:

for line in open('test.txt').readlines():
    for word in arr:
        if line.startswith(word):
            applist.append(line)

Now, if I do not have a line with any of the strings in the arr list, then I want to append 'NULL' to applist instead. I tried:

for line in open('test.txt').readlines():
    for word in arr:
        if line.startswith(word):
            applist.append(line)
        elif word not in 'test.txt':
            applist.append('NULL')

But it obviously doesn't work (it inserts many unnecessary NULLs). How do I go about it? Also, there are other lines in the text file besides the three lines starting with the strings in arr. But I want to append only these three lines. Thanks in advance!

Upvotes: 0

Views: 5893

Answers (2)

HalR
HalR

Reputation: 11073

I think this might be what you are looking for:

found1 = NULL
found2 = NULL
found3 = NULL
for line in open('test.txt').readlines():
  if line.startswith(arr[0]):
     found1 = line;
  elif line.startswith(arr[1]):
     found2 = line;
  elif line.startswith(arr[2]):
     found3 = line;
  for word in arr:

applist = [found1, found2, found3]

you could clean that up and make it better looking, but that should give you the logic you're going for.

Upvotes: 0

FUD
FUD

Reputation: 5184

for line in open('test.txt').readlines():
  found = False
  for word in arr:
    if line.startswith(word):
        applist.append(line)
        found = True
        break
  if not found: applist.append('NULL')

Upvotes: 1

Related Questions