Home > database >  Reading CSV in Python and Outputting Specific Data
Reading CSV in Python and Outputting Specific Data

Time:07-29

I am working on a python script that reads user input and returns values from the CSV. I am able to return all values, but I only need a few. There are many columns in the CSV, examples are:

LOC_NBR LOC_NAME ALPHA_CODE FRANCHISE_TYPE FRANCHISEE_LAST_NAME

My code is below, what could I add to this to only pull the data for say LOC_NBR, LOC_NAME, and FRANCHISE_TYPE? Right now if I change the print statement, I get a data type error because the fields are STR in the csv.

import csv

store_Num = input("Enter 5-Digit Store Number: ")
    
with open('StoreDirectory.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)

    found = False
    
    for line in reader:
            if line[0] == store_Num:
                    print(line)
                    found = True
                    break
    if not found:
            print(store_Num, "not found")

CodePudding user response:

The fastest (or most convenient) way to do this might be to use the pandas module and import the data into a dataframe.

import pandas as pd

df = pd.read_csv('data.csv')

from here you can extract rows or columns as you like.

column = "column_name"
row = 2
print ( df[column][row] )

Ideally the dataframe needs column headers which will make life easy.

CodePudding user response:

Using Python csv:

cat csv_test.csv 
first,second
1, 1
3, 4

import csv

with open("csv_test.csv") as csv_file:
    c = csv.DictReader(csv_file)
    for row in c:
        if int(row["first"]) == 3:
            print(row["first"], row["second"])

3  4
  • Related