0

I have a txt file that I need to parse. I read the file in as a list, then strip the extra spaces. From there I need to remove one line. It contains "-----------------------" I am trying to get rid of it, but when I attempt to do the code below it doesn't seem to work correctly. When I print out the value of the line in the if statement it prints successfully, but won't delete that element from the list. If I remove it at the end, it works. What am I dont wrong?

   with open("somefile.txt") as f:
        output = f.readlines()
    
    for i,line in enumerate(output):
    
        if '-' in line:
            #print("this is the line " + str(line) )
            output.remove(line)
            #output.pop(i)
            continue
    
        output[i] = (" ".join(line.split()))
        output[i] = i.split(" ")[:2]
    
    
    #output.pop(1)
    #output.pop(2)
    
    print(output)
NerdGuy021
  • 59
  • 2
  • 6
  • 2
    You're trying to change the same list you're iterating? Sounds dangerous something will go wrong. Why not filter it? https://stackoverflow.com/questions/5640630/array-filter-in-python – Bojan Kogoj Mar 24 '21 at 14:04
  • @BojanKogoj good catch – Vova Mar 24 '21 at 14:07

1 Answers1

0

Try something like that:

with open("your_file.txt") as f:
    output = [" ".join(line.split()) for line in f.readlines() if '-' not in line]

print(output)

but, that command doing nothing:

" ".join(line.split())

first you split a line by " " and then join it with " "

second, you're trying to split int value with that command, what rises exception:

output[i] = i.split(" ")[:2]
Vova
  • 3,117
  • 2
  • 15
  • 23