Home > front end >  How to select one specific parameter from csv file loaded into Python in single row?
How to select one specific parameter from csv file loaded into Python in single row?

Time:11-05

I'm trying to get a single parameter from csv file loaded into python. I created rows and appended into row variable File is saved like Column : Fruit, Amount, Price Apple, 30, 0.5 enter image description here

rows = []
with open("practice_file.csv", 'r') as file:
    csvreader = csv.reader(file)
    header = next(csvreader)
    for row in csvreader:
        rows.append(row)
    print(rows[1])

If I do this I get an output, [Apple, 30, 0.5] How can I get an output which only pulls "Apple"?

Thanks in advance

I couldn't get anything to solved.

CodePudding user response:

In your code rows[i] represents an entire row of values. To get an individual column value from any particular row you would need to index into your row (row[i][j])

In your case (assuming your data is exactly as your image shows), this should work:

rows = []
with open("practice_file.csv", 'r') as file:
    csvreader = csv.reader(file)
    header = next(csvreader)
    for row in csvreader:
        rows.append(row)
    print(rows[0][0])

You could also store just one value from each row to begin with (instead of storing the entire row)

rows = []
with open("practice_file.csv", 'r') as file:
    csvreader = csv.reader(file)
    header = next(csvreader)
    for row in csvreader:
        rows.append(row[0])
    print(rows[0])

CodePudding user response:

Since the file has a header use DictReader and pull the value using the header/column name as each row will be a dict of form `{"Fruit": col_val, "Amount": col_val, "Price": col_val}.


rows = []
with open("practice_file.csv", 'r') as file:
    csvreader = csv.DictReader(file)
    for row in csvreader:
        rows.append(row["Fruit"])
    print(rows)
  • Related