1

I want to be able to parse csv files that will be maintained outside of our software group. A sample csv may contain:

temperature,50,55,56
color,blue
count,10
dummy,line

The code will search the file for a list of ints called temperature, a string called color and an int called count. Then it will assign the values [50, 55, 56], 'blue' and 10 respectively.

  • The row ordering in the csv files is arbitrary (e.g. sometimes 'color' could come before 'temperature').
  • The object names are predefined but the values will vary between csv files.
  • The csv files will always contain the object names that the python code searches for.
  • The csv files may contain extra data rows that are not useful to the python code.
  • The object names will always be in the first column of the csv.

I have seen other code examples that search for specific object types, or objects in predefined row positions. However, I need a solution that is more robust.

Any help will be appreciated. Please let me know if you need clarification and I will edit.

2
  • What did you try before post this question ? Commented Nov 14, 2015 at 3:05
  • @Zulu I tried something similar to Michael's below but without first initializing the object names and not knowing how to return a list who's size would vary before csv files. So yes, it was lengthy and messy. Commented Nov 14, 2015 at 13:53

1 Answer 1

1

All you need is something like the following:

import csv

with open('file.csv', 'r') as f:
    reader = csv.reader(f)

    dummy = []
    temperature = []
    color = ''
    count = 0

    for row in reader:
        try:
            if row[0] == 'temperature':
                temperature = map(int, row[1:])
            elif row[0] == 'color':
                color = row[1]
            elif row[0] == 'count':
                count = int(row[1])
            else:
                dummy.append(row)

        # for robustness, let's catch the case where a row
        # may be malformed or does not contain more than 1 column
        except IndexError:
            dummy.append(row)
Sign up to request clarification or add additional context in comments.

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.