5

I wish to select a specific row and column from a CSV file in python. If the value is blank, I want to perform one action, and if the value is not blank, I want to perform another action.

I think the code should look something like this:

inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')
for row in reader:
    if row[5][6] == '':              ==>  (I mean select value the 5th row and 6th column)
        (do this)
    else:
        (do that)

Any help or guidance on this topic would be helpful -- I've done a similar task using lists; however, since the CSV file is raw, I don't know what to do.

1
  • You mean your action is manipulate one field of the row? Commented Aug 4, 2014 at 2:26

5 Answers 5

12

When you think CSV, think pandas.

import pandas as pd

df = pd.read_csv('path/to/csv')

if df.iloc[5, 6]:
    # do stuff
else
    # do some other stuff
Sign up to request clarification or add additional context in comments.

1 Comment

Pandas work with many other file seperators: csv, or tab delimited, or any other separator, or even regex.
2

Both inspectorG4dget and Oscar Lopez have the right idea, but there are flaws in their solutions. Thus, I present my own.

The general idea is that csv.reader is just a special file object that automatically splits things on commas. Treat it like any other file object. If you want the nth line, iterate until you hit the nth line.

with open('inputFile', rb) as f:
  reader = csv.reader(f)
  for i, l in enumerate(reader):
    if i==5:
      try:
        print l[6]
      except IndexError:
        print "Nothing here!"

A few notes:

  • I use a with block so that the file is safely closed on the completion of this code. You can always call file.close yourself, but this is better practice.
  • I wrap the access to the 6th column of the line in a try...except because, well, there might not be a 6th column. Better safe than sorry.

Comments

1

Try this:

inputFile = 'example.csv'
reader = csv.reader(inputFile, 'rb')

for i, row in enumerate(reader):
    if i == 5:      # here's the row 5
        data = row.split(',')
        if data[6]: # here's the column 6
            pass    # if the position [5][6] is non-empty do something
        else:       # otherwise
            pass    # do something else

Comments

1

The problem that you are running into, is that you are looking at the character at index 6, of the value at column 5, in every row of the csv file. Instead, what you want to do is look at the 6th row of the file, and the 5th column of that row

import csv
def getCell(infilepath, row, col):
    with open(infilepath) as infile:
        reader = csv.reader(infile)
        try:
            for i in range(row-1):
                next(reader)
        except:
            print(infilepath, "does not have ", row, " rows of data")
            return
        try:
            line = next(infilepath)
        except:
            print(infilepath, "does not have ", row, " rows of data")
            return
        col -= 1
        if len(line) < col:
            print(infilepath, "does not have ", col, " columns of data on row ", row)
            return
        return line[col]

Now that we have a way to get the data in the required cell, we can continue:

value = getCell('example.csv', 5, 6)
if value is not None:  # the value actually exists
    if value == '':
        # do this
    else:
        # do that

Comments

1

My names.csv file.

number;first_name;last_name
1;Baked;Beans
2;Lovely;Spam  
3;Wonderful;Spam
4;Up;Spam
5;Baked;Beans
6;Lovely;Spam
7;Wonderful;Spam
8;Down;Spam
9;Baked;Beans

My code in python

import csv
L = [0, 5, 7]

with open('names.csv',"r") as f:
    r = csv.DictReader(f, delimiter =";")
    for i, line in enumerate(r):
        if i in L:    # or (i+2) in L: from your second example
            print (line)
            print (line['first_name'], line['last_name'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.