Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select a specific CSV row with python

Tags:

python

csv

I am brand new to learning how to use Python (or coding in general) and I am attempting to make a Twitter bot that posts quotes from one of my favorite TV characters "Michael Scott".

I have all of my quotes in a CSV file. The problem I am trying to tackle right now is how do I select a specific row within the CSV, grab a quote I have stored in that row, and save it as a variable.

I have looked at other documentation on selecting specific rows but they all seem to be trying to do more than just pick a row.

This is the code I have. It is returning all of the quotes that are stored in the CSV.

import csv

with open('data.csv') as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        print(row[2])

--- edited to show the structure of the CSV ---

id_serial,id_season,quote,file_path,id_group,trigger_time
1,S1E01,"People say I am the best boss. They go ""god we've never worked at a place like this before. You're hilarious. And you get the best out of us.""",,001,09:00 AM EST
2,S1E01,I think this pretty much sums it up,/home/pi/Desktop/OfficialDundies/media/001.png,001,11:00 AM EST

My apologies if I am not specific enough. I am still learning a lot here. :)

like image 389
Zach Pi Avatar asked May 24 '26 21:05

Zach Pi


1 Answers

import csv

with open('data.csv') as csvDataFile:
    data = list(csv.reader(csvDataFile))

print(data)

Now you've got everything in the list data:

[['id_serial', 'id_season', 'quote', 'file_path', 'id_group', 'trigger_time'], ['1', 'S1E01', 'People say I am the best boss. They go "god we\'ve never worked at a place like this before. You\'re hilarious. And you get the best out of us."', '', '001', '09:00 AM EST'], ['2', 'S1E01', 'I think this pretty much sums it up', '/home/pi/Desktop/OfficialDundies/media/001.png', '001', '11:00 AM EST']]

The first index is for each line, the second index for each column of that row. To get the quote, the second index has to be 2.

You could select a random row (for a random quote) with:

import random
i = random.randint(1, len(data) - 1)

randint(1, len(data) - 1) will return a random integer starting at index 1 since the first line of your CSV file contains the column captions.

We can now print the randomly selected quote:

print(data[i][2])
like image 81
finefoot Avatar answered May 27 '26 10:05

finefoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!