2013-06-29 23 views
0

我想打開一個文件,並從行中獲得所有無效id的列表..一次我找到無效的id ..i想要刪除整行(它有多個ID),如果一個ID是無效的...我可以達到找到無效ID的點..我需要輸入如何從文件中刪除行或寫入重新生成的好行到一個新的文件..我有樣本輸入和預期輸出下面...任何人都可以提供輸入?如果行中的一個id是無效的,刪除行中的行

import os 
import sys 
import time 
import simplejson as json 
from sets import Set 
import operator 
import unicodedata 
import getopt 

''' 
list.txt 

350882 348521 350166 
346917 352470 
360049 
''' 

''' 
EXPECTED OUTPUT:- 
346917 352470 
360049 
''' 
def func (GerritId): 
    if GerritId == '350166': 
     value = "GERRIT IS INCOMPLETE" 
    else: 
     value = "GERRIT LOOKS GOOD" 
    return value 

gerrit_list=[] 
invalid_gerrit = [] 
cherry_pick_list = [' '] 
with open('list.txt','r') as f : 
    for line in f : 
     gerrit_list = line.split(' ') 
     print "line" 
     print line 
     print "gerrit_list" 
     print gerrit_list 
     for GerritId in gerrit_list : 
      GerritId = GerritId.strip() 
      print "GerritId" 
      print GerritId 
      #returnVal = RunCheckOnGerrit_Module.GerritCheck(GerritId) 
      #GerritInfoItem['GerritId'] = GerritInfoItem['GerritId'] + "\n" 
      returnVal = func(GerritId) 
      #print "returnVal" 
      #print returnVal 
      if returnVal in ('GERRIT IS INCOMPLETE' or 'NOTHING IS SET' or 'TO BE ABANDON OR NEEDS RESUBMISSION') : 
       print returnVal 
       invalid_gerrit.append(GerritId) 
      else: 
       print returnVal 

print invalid_gerrit 

with open('list.txt','r') as f : 
    for line in f : 
     #delete the whole line if any invalid gerrit is presnet 
     gerrit_list = line.split(' ') 
     print "line" 
     print line 
     print "gerrit_list" 
     print gerrit_list 
     for GerritId in invalid_gerrit: 
      GerritId = GerritId.strip() 
      #delete the whole line if any invalid gerrit is presnet 
+0

http://stackoverflow.com/questions/4710067/deleting-a-specific-line -in-a-file-python應該給你你需要的東西。 – ojs

+0

@ojs - 這將有助於刪除一條線..我還有一個問題,其中我的文件中的行是ID ...我需要刪除該行,如果任何的ID是無效的 – user2341103

+0

然後,而不是'if line !=「nickname_to_delete」+「\ n」:'測試id是否在行中。閱讀列表中的行,並檢查列表中是否存在無效標識。 – ojs

回答

0

這是一個原始代碼,會寫,只有有效身份證線到一個新的文件:

f_write = open('results.txt', 'wb') 

with open('list.txt','r') as f : 
    for line in f : 
     #delete the whole line if any invalid gerrit is presnet 
     gerrit_list = line.strip().split(' ') 

     ifvalid = True 
     for gerrit in gerrit_list: 
      try: # check if invalid gerrit is present 
       invalid_gerrit.index(gerrit) 
       ifvalid = False 
       break 
      except: 
       pass 

     if ifvalid: 
      f_write.write(line) 

f_write.close()