TangerCity
TangerCity

Reputation: 845

How to use the set intersection method in python

at_set = {'Num1', 'Num2', 'Num3'}
for files in os.listdir(zipped_trots_files):
    zipped_path = os.path.join(zipped_trots_files, files)
    with open(zipped_path, 'r') as output:
        reader = csv.reader(output, delimiter = '\t')
        for row in reader:
            read = [row for row in reader if row] 
            for row in read:
                if set(row).intersection(at_set):
                    print(row)

I guess i'm using the intersection function wrong...can someone see it? I'm trying to print only the rows who contain either Num1, Num2 or Num3

When I do print I receive nothing...

Upvotes: 0

Views: 100

Answers (1)

Matt Wang
Matt Wang

Reputation: 318

there are duplicated iterations. You need to remove the excessive iterations or go back to the beginning of reader by calling output.seek(0).

at_set = {'Num1', 'Num2', 'Num3'}
for files in os.listdir(zipped_trots_files):
    zipped_path = os.path.join(zipped_trots_files, files)
    with open(zipped_path, 'r') as output:
        reader = csv.reader(output, delimiter = '\t')
        for row in reader:
            if row and set(row).intersection(at_set):
                print(row)

Upvotes: 1

Related Questions