我只想从我的测试文件中删除一个搜索行

I want to delete just a one searched row from my test file

下面是我的代码和文件数据。我有一个名为 test 的文件。我试图在第一列中找到一个数字。如果在任何行中找到该数字,我想删除该行。

def deleteline():
n=5
outfile=open('test.txt','r+')
line = outfile.readline()
while line !='':
    lines= line.rstrip('\n')
    listline=lines.split(',')
    num=int(listline[0]) 
    if n==num:       
       print(listline[1])    
       outfile.write(lines)
    else:
       print("no")
    line= outfile.readline()
outfile.close()

根据 Simon 在上述评论中的建议,从 this 答案中,修改检查条件如下:

with open("test.txt", "r") as f:
    lines = f.readlines()
with open("test.txt", "w") as f:
    for line in lines:
        tempLine=line.strip("\n")
        tempLine=tempLine.split(',')
        if int(tempLine[0]) != 4:
            f.write(line)

这应该可以解决您的问题:

def deleteline():

    n = 5
    outfile = open('test.txt', 'r')
    lines = outfile.readlines()
    outfile.close()
    outfile = open('test.txt', 'w')
    for line in lines:
        lineStrip = line.rstrip('\n')
        listLine = lineStrip.split(',')
        num = int(listLine[0])
        if(num == n):
            outfile.write('')
        else:
            outfile.write(line)
    outfile.close()