0

I've got a .csv file and I need to get some information from it. If I open the file, I can see two lines in it, that says "data" and "notes", and I need to get the information that these two variables have.

When I open the .csv file, it shows these lines:

data = 
[0,1,2,3,4,5,3,2,3,4,5,]

notes = [{"text": "Hello", "position":(2,3)}, {"text": "Bye", "position":(4,5)}]

To open the file I use:

import csv

class A()
  def __init__(self):
    #Some stuff in here

  def get_data(self):
    file = open(self.file_name, "r")
    data = csv.reader(file, delimiter = "\t)
    rows = [row for row in data]

Now, to read the information in data, I just write:

    for line in row[1][0]:
      try:
        value_list = int(line)
        print value_list

      except ValueError:
        pass

And, with this I can create another list with these values and print it. Now, I need to read the data from "notes", as you can see, it is a list with dictionaries as elements. What I need to do, is to read the "position" element inside each dictionary and print it.

This is the code that I have:

   for notes in row[3][0]:
     if notes["position"]:
       print notes["position"]

But this, gives me this error: TypeError: string indices must be integers, not str

How can I access these elements of each dictionary and then print it? Hope you can help me.

This is the .csv file from where I am trying to get the information.

enter image description here

5
  • That doesn't appear to actually be a CSV file Commented Jun 9, 2016 at 21:05
  • This problem is notes is a string not a dict Commented Jun 9, 2016 at 21:07
  • Well, it is. Is just that at the beginning it has one column only. After these lines, is a common .csv file. Commented Jun 9, 2016 at 21:08
  • @PabloFlores that is not the preferred way to use csv reader >> remove from class. It is not reccommded to have one function class. Use functions. Commented Jun 9, 2016 at 21:12
  • @PabloFlores -- what is row in row[1][0]? Commented Jun 9, 2016 at 21:15

1 Answer 1

1

You can change the last part of your code to:

for note in eval(rows[3][0].strip("notes = ")):
    if note["position"]:
        print note["position"]

If you need the position to be an actual tuple instead of a string, you can change the last line to:

print tuple(note["position"])
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. Isn't "rows" a list? If it is, then strip will give me a syntax error. Isn't it?
@PabloFlores - It is, but rows[3][0] is a string, and that's what you're running strip on. Test the code, it works.
Thank you. You helped me a lot.

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.