简体   繁体   中英

Searching for keywords in CSV file columns

I need to search a column in a CSV file for a specific keyword and if it is found – get a data from the whole row. The file I'm working with is my school's schedule, so it's pretty big.

import csv

with open('plan.csv', 'rt', encoding='windows 1250') as fileinput:

    # In the code below I first create a list of groups, skipping
    # duplicates, so that user can later select a group to show it's 
    # details.

    reader = csv.reader(fileinput, delimiter=';')

    groups = []
    #filling up the list with groups
    for row in reader:
        if row[12] in groups:
            continue
        elif row[12] is '':
            continue
        else:
            groups.append(row[12])

    # Just to make sure there's something in 'groups'
    print(groups[1:])

    # Then I'm asking a user to select the group.
    # user_choice = input('Group?')

    # setting up user_choice to make things simpler for testing
    user_choice = '3I4'

    # The last part is searching groups column (column index 12) for a 
    # specific group and if found – print whole row and continue 
    # the search.
    for row in reader:
        if row[12] is user_choice:
            print(row)
            continue
        else:
            print('not found')

After running the last part of code I receive no console output at all, neither the rows for group, nor "not found".

I believe the reason you are seeing no output is because csv.reader returns an iterator and you have a loop prior to your print statements that iterates through all the lines. The second time you iterate over all the lines the iterator has no more lines to return so it never enters that for loop. I could be wrong but to fix it either save all the lines into an array or re-instantiate the csv.reader before the second for loop.

 reader = csv.reader(fileinput, delimiter=';')

The fileinput you opened was already consumed in the first for loop. You need to re-open the file or reset the pointer that seeks the file. Re-instantiate csv.reader only doesn't solve the problem because it still used the consumed fileinput . After the first for loop and before the second for loop :

fileinput.seek(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM