54m
54m

Reputation: 767

How to split a file in python

I am trying to split 2 lists, compare them and make a new list without the succesfully compared items in 2 lists.

So lets say List_1.txt =

Failed = abc
Failed = hfi
Failed = kdi

and List_2.txt =

1:1:1 - jdsfjdf
2:2:2 - iidf
3:3:3 - abc
6:3:1 - hfi
8:2:1 - kdi
3:1:5 - dua
3:1:2 - dfh

I want to compare those lists and make a new_list2 without the list_1 entries.

what I tried was:

treinrit = open('List_1', 'r')
lijna = treinrit.readlines()
treinrit.close()

annuleer_treinrit = open('List_2', 'r')
lijnb = annuleer_treinrit.readline()
annuleer_treinrit.close()

lijsta = []
lijstb = []

for a in lijna:
    clean = a.split(' - ')
    print(lijsta)

for b in lijnb:
    lijstb.append(lijnb.split(": "))

I just cant get the list to split properly. I only need the last bit of each file to compare but I don't know how.

Upvotes: 0

Views: 88

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 60944

with open('File1', 'r') as f1:
    f1_stored = []
    for line in f1:
        f1_stored.append(line.split('=')[1].strip())
    with open('File2', 'r') as f2;
        output = []
        for line in f2:
            if not any(failed in line for failed in f1_stored):
                output.append(line)

The do what you want with output

Upvotes: 1

Gábor Erdős
Gábor Erdős

Reputation: 3689

Something like this

bad_stuff = []
with open('List_1', 'r') as fn:
    for line in fn:
        bad_stuff.append(line.split('=')[1].strip())


with open('List_2', 'r') as fn:
    for line in fn:
        if line.split(':')[1].strip() not in bad_stuff:
            print(line)

The list bad_stuff will have all the elements from the first file after the = sign (like abc, hfi and kdi)

Then check the second file, and only print if the part after the : sign is not in the list bad_stuff

Upvotes: 1

Related Questions