How to select a specific CSV row with python

时间:2019-04-16 23:17:42

标签: 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. :)

2 个答案:

答案 0 :(得分:1)

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])

答案 1 :(得分:1)

If I understand your question correctly, you want to save value of a column named "quote" occurring at row number say row_num in your csvfile(let's name it "csv_file_name.csv"). You can achieve this through pandas. Read the csv file and get the quote in a specific row using iloc.

import pandas as pd
row_num = 2 #say you want quote from 3rd row
data = pd.read_csv("csv_file_name.csv") # give path of your .csv file here
quote_var = data.iloc[row_num]['quote']
quote_var

Hope this helps.