如果行中的某个ID无效,则从文件中删除行

时间:2013-06-29 00:58:36

标签: python

我正在尝试打开一个文件并从其中的行中获取所有无效ID的列表。我发现无效的ids ..我想删除整行(它有多个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

1 个答案:

答案 0 :(得分:0)

这是一个粗略的代码,它会将只有有效ID的行写入新文件:

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