Unable to ready CSV Headers

Error:
Column ‘Stock’ not found in CSV file.
No matching data found.

Note:
Headers within output.csv are located on line 1.

Code:

import csv

def filter_csv_column(csv_file, column_name, keyword):
    filtered_data = [ ]

    with open(csv_file, 'r') as file:
        reader = csv.DictReader(file)
        headers = reader.fieldnames

        if column_name not in headers:
            print(f"Column '{column_name}' not found in CSV file.")
            return filtered_data  # Return empty list if column name is not found

        filtered_data.append(headers)  # Add the header row to filtered data

        for row in reader:
            if keyword.lower() in row[column_name].lower():
                filtered_row = [row[column] for column in headers]
                filtered_data.append(filtered_row)

    return filtered_data

csv_file = '/path/to/file/input.csv'
column_name = 'Stock'  # Specific column name to filter
keyword = '7'  # Keyword to match in the specified column

filtered_data = filter_csv_column(csv_file, column_name, keyword)

if len(filtered_data) == 0:
    print("No matching data found.")
else:
    for row in filtered_data:
        print(row)
~

I’m guessing that the case doesn’t match and/or there are spaces around the header name.

Stock;UPC Code;Product Description;

I’m at a loss…

“CSV” stands for Comma-Separated Values. ‘;’ is a semicolon, not a comma.

Printing out reader.fieldnames would’ve helped you spot that.

1 Like

Captain Obvious just stopped by and shmacked me in the face. Thank you!!! =))