1

This is my code and file data given bellow. I have file with the name of test. In which I’m trying find a num in first column. If that number is found in any line, I want to delete that row.

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()
Usama ali
  • 115
  • 1
  • 8
  • Check https://stackoverflow.com/questions/4710067/using-python-for-deleting-a-specific-line-in-a-file and replace the line of code that checks if the line in the file should be deleted – Simon Crane Sep 29 '19 at 16:39

2 Answers2

1

This should solve your problem:

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

As suggested by Simon in above comment, from this answer, modify the check condition like 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)
  • its show me this error 74, in delete if int(tempLine[0]) != 5: ValueError: invalid literal for int() with base 10: 'sally LM' – Usama ali Sep 30 '19 at 03:32