Evan Cooper
Evan Cooper

Reputation: 146

Searching in a CSV file - python

I have a csv file containing a lot of songs. Each row has 5 columns, which are:

Artist | Song Title | Album Name | Genre | Year

I would like to open a CSV file, and then search all the song names to bring up results. Therefore, if I search for 'heaven', I would want one of the results to turn up as "Stairway to Heaven by Led Zeppelin". I am unaware of how to specify specific columns of CSV file when performing a search, and returning the results.

I am still new to python so a simple answer would be best, if possible

Thank you in advance!

Upvotes: 0

Views: 3552

Answers (3)

Mauro Baraldi
Mauro Baraldi

Reputation: 6575

Example of a file named songs.csv

from StringIO import StringIO

s = """
Artist;Song Title;Album Name;Genre;Year
Rush;Tom Sawyer;Moving Pictures;Progressive Rock;1981
Led Zeppelin;Black Dog;Led Zeppelin IV;Hard Rock;1970
AC/DC;Back in Black;Back in Black;Hard Rock; 1980
"""
songs_file = StringIO(s)

Load data file into a csv.DictReader.

from csv import DictReader

songsdb = [i for i in DictReader(songs_file, delimiter=';')]

def search(criteria):
    for row in songsdb:
        for data in row.values():
            if criteria in data:
                print row

search('Black')

{'Album Name': 'Led Zeppelin IV', 'Genre': 'Hard Rock', 'Year': '1970', 'Song Title': 'Black Dog', 'Artist': 'Led Zeppelin'}
{'Album Name': 'Back in Black', 'Genre': 'Hard Rock', 'Year': ' 1980', 'Song Title': 'Back in Black', 'Artist': 'AC/DC'}

Upvotes: 1

Tim Zimmermann
Tim Zimmermann

Reputation: 6420

To search for songs, you can use this:

import sys
import csv

if len(sys.argv) < 2:
    print 'Please provide a song name to search for.'
    sys.exit(-1)

match = None
with open('songs.csv') as f:
    r = csv.reader(f, delimiter='|')
    next(r, None) # skip header
    for row in r:
        if sys.argv[1] in row[1]:
            match = row[:]
            break

if match:
    print '%s by %s' % (match[1].strip(), match[0].strip())
else:
    print '%s not found.' % (sys.argv[1])

Call it like this:

python search.py Heaven

Upvotes: 1

myersjustinc
myersjustinc

Reputation: 714

As Kevin said in his comment, you'll want to use the csv module for this one.

Here are some examples for how to use it.

If you want to be able to specify names of columns (and not just their positions), you'll want to take a look at csv.DictReader, which works just like the csv.reader used in the examples from my first link, but with dicts (mappings of column names to column values) rather than lists of the column values in order.

Upvotes: 0

Related Questions