0

我正在尝试打开一个文件并从其中的行中获取所有无效 id 的列表..一旦我找到无效的 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
4

1 回答 1

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()
于 2013-06-29T01:27:35.303 回答