2013-05-16 31 views
0

我有一组字符串和另一个动态列表的列表:如果线路在文本文件中不存在的 - 蟒蛇

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 '来代替。我试过:

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中的字符串开始的三行之外,文本文件中还有其他行。但我只想追加这三行。提前致谢!

+0

'elif word不在'test.txt'中:''''test.txt'这里只是一个字符串。不是来自文件或其他内容的文件。 – soon

回答

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

我应该提到除了以arr中的字符串开始的文本文件外,还有其他行。您的代码也会为所有其他行插入NULL。 – user2251144

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] 

你可以清理一下,使它更好看,但应该给你你要的逻辑。

+0

仍然不起作用:(在这种情况下,NULL不会被追加。 – user2251144

+0

也许我不明白你在做什么。你总是想要追加一个NULL吗?或者你是否想要一个null行不匹配? – HalR

+0

考虑到在文本文件中没有以'sample2'开始的行,所以我想要的是['sample1'开始的行,'NULL','sample3开始的行' ]。在文本文件中会有其他行,但我不想考虑它们,只有这三行。 – user2251144