JadenBlaine
JadenBlaine

Reputation: 275

Searching a specific columns of a table for not matching items

with open("test.txt", "r") as test:
    reader = csv.reader(test, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
       for field in row:
            if field not in keywords:
                writer.writerow(row)
                break

It seems that this code writes out every row multiple times. I guess that it looks up every single field in each column. How can I specify a single column?

So this is the code I am using right now and it seems that it misses a few rows where the keyword is not present in any column.

table = open("table.txt", "w")
with open("test.txt", "r") as test:
    reader = csv.reader(test, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

Upvotes: 3

Views: 368

Answers (1)

Kasravnd
Kasravnd

Reputation: 107337

You can use zip to get your columns then.You can use a generator expression within all function for checking that all the elements mett the condition :

with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = zip(*csv.reader(Spenn, delimiter="\t"))
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

But if you just want to write the rows that meet the condition you can use the following code :

with open("test.txt", "r") as Spenn,open("test.txt", "r") as table:
    reader = csv.reader(Spenn, delimiter="\t")
    writer = csv.writer(table, delimiter="\t")
    for row in reader:
        if all(field not in keywords for field in row):
            writer.writerow(row)

Upvotes: 1

Related Questions