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

2024-10-01 05:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图打开一个文件,并从其中的行中获取所有无效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

Tags: inimporttxtidforifvalueas
1条回答
网友
1楼 · 发布于 2024-10-01 05:00:40

这是一个粗略的代码,它将只使用有效的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()

相关问题 更多 >