Iterate over a file

Viewed 102

I want to open a file in Python. For every line in the file split it with line.split(" "),
so it will access the first word.

Then check if the word is equal to a given string "TEST". If this is the case delete the line else just keep it.

I have tried using readlines() to read the lines. That worked, but then I couldn't figure out how to delete the entire line.

This is my code so far

def delete_client(client):
    f = open("clients.md", "r")
    data = f.readlines()

    f = open("clients.md", "w")
    for line_counter in range(len(data)):
        splitted_line = data[line_counter].strip("\n").split()[0]
        print("\n" + splitted_line)

        if client == splitted_line:
            print("Equal to client")
            f.write("HELLO")
        else:
            print("Not equal to client")

    f.close

delete_client("DELETE_ME")

The clients file

first 192.168.0.14 Lukas administrator
another text 192.168.0.14 Lukas administrator
DELETE_ME 192.168.0.14 Lukas administrator
fourth 192.168.0.14 Lukas administrator
4 Answers

The else: block should write the line to the file. And get rid of the line that writes HELLO to the file (unless you really want this to replace the deleted lines).

        if client == splitted_line:
            print("Equal to client")
        else:
            print("Not equal to client")
            f.write(data[line_counter])

Use list comprehension to create another list which does not contain the rows you want to delete and write those rows back to the original file.

def delete_client(client):
  with open('clients.md', 'r') as f:
    data = f.readlines()

  lines_to_keep  = [line for line in data if line.split(' ')[0] != client]
  
  with open('clients.md', 'w')as f:
    f.writelines(lines_to_keep)
    
delete_client("DELETE_ME")

You cannot simulate your desired behavior using:

import fileinput

for line in fileinput.input(files=('clients.md'), inplace=True, backup='.old'):
    if not line.startswith('DELETE_ME'):
        print(line, end='')

Alternatively the "plain old" way works as well;

with open('clients.md', 'r') as in_file:
    content = in_file.readlines()
    
with open('clients.md', 'w') as out_file:
    out_file.writelines(filter(lambda x: not x.startswith('DELETE_ME'), content))

Also when reading/writing files you should use with-blocks to assure that filepointers are opened/closed correctly.

You can use:

def dc(word):
  with open("text.txt") as f:
    i =  [l for l in f if not l.startswith(word)]
  with open("text.txt", "w") as w:
    print(*i)
    for l in i:
      w.write(l)
  
word = "DELETE_ME"
dc(word)

Demo

Related