如果文本文件中没有行 - python

时间:2013-05-16 01:27:18

标签: python-2.7

我有一个包含一组字符串和另一个动态列表的列表:

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

我正在逐行读取文本文件,如果一行以arr中的任何字符串开头,那么我将其附加到applist,如下所示:

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

现在,如果我没有arr列表中任何字符串的行,那么我想将'NULL'添加到applist中。我试过了:

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')

但它显然不起作用(它插入了许多不必要的NULL)。我该怎么办呢?此外,除了以arr中的字符串开头的三行之外,文本文件中还有其他行。但是我想只追加这三行。提前谢谢!

2 个答案:

答案 0 :(得分:1)

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')

答案 1 :(得分:0)

我认为这可能就是你要找的东西:

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]

你可以清理它并让它看起来更好看,但这应该给你你想要的逻辑。