SPORKEATER
SPORKEATER

Reputation: 21

How to parse and print fields from CSV data in python

I'm dealing with an application that exports text as as CSV type data. The text is broken up into fields where there was a hard return. I have been trying to use pythons CSV to restore the text.

This is an example of the text:

{"This is an example", "of what I what I have to deal with.  ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}

What is the best way to read this output this text like so:

This is an example
of what I have to deal with.
Please pick up the following:
eggs
milk
Thanks for picking up the groceries for me

I have tried a number of ways that just haven't been quite right.

Here is what I am doing so far:

import csv
import xlrd
book = xlrd.open_workbook("book1.xls")
sh = book.sheet_by_index(0)
cat = 'Mister Peanuts'

for r in range(sh.nrows)[0:]:
    cat_name = sh.cell_value(rowx=r, colx=1)
    cat_behavior = sh.cell_value(rowx=r, colx=5)

    if sh.cell_value(rowx=r, colx=1) == cat :       
        csv_reader = csv.reader( ([ cat_behavior ]), delimiter=',') 
        for row in csv_reader:

                for item in row:
                        item = item.strip()
                        print(item)
            pass    
    pass

So, the actual cell value that is returned for cat_behavior is the following:

['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', '  "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']

I am now trying to take the above and run in through csv.reader to sanitize it and print it to a text file. I am now trying to make the (item) look normal.

Upvotes: 2

Views: 2081

Answers (4)

John Machin
John Machin

Reputation: 82934

Please explain what you have got to start with.

x = {"This is an example", ......., "Thanks for picking groceries up for me"}

That looks like a set. Then you pass [x] as the first arg of csv.reader!! That doesn't work:

[Python 2.7]
>>> import csv
>>> x = {"foo", "bar", "baz"}
>>> rdr = csv.reader([x]) # comma is the default delimiter
>>> list(rdr)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected string or Unicode object, set found
>>>

You say "application that exports text as as CSV type data" -- what does "exports" mean? If it means "writes to a file", please (if you can't follow the examples dotted all over the web) give us a dump of the file to look at. If it means "method/function returns a python object", please do print(repr(python_object)) and update your question with a copy/paste of the print output.

What documentation about the application output do you have?

Update after comments and question edited:

You say that the cell value "returned" was:

['{"Mister Peanut spent 3.2 hours with {bojangles} fighting', ' "', ' "litter box was cleaned, sanitized and replaced "', ' " Food was replensished - with the best food possible"', ' ', ' "technician - don johnson performed all tasks"}']

This looks like what you printed after passing the ACTUAL data through the CSV mangle, not the raw value extracted by xlrd, which certainly won't be a list; it would be a single unicode object.

In case you didn't read it before: Please explain what you have got to start with.

Do you think it possible to do these:

(1) please do print(repr(cat_behavior)) and update your question with a copy/paste of the print output.

(2) say what documentation you have about the application that creates the Excel file.

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342393

>>> s
'{"This is an example", "of what I what I have to deal with.  ", "Please pick up th following:", "eggs", "milk", "Thanks for picking groceries up for me"}'

>>> print s.replace(",","\n").replace("{","").replace("}","").replace('"',"")
This is an example
 of what I what I have to deal with.
 Please pick up th following:
 eggs
 milk
 Thanks for picking groceries up for me

>>> open("output.csv","w").write( s.replace(",","\n").replace("{","").replace("}","").replace('"',"") )

Upvotes: 0

unutbu
unutbu

Reputation: 879641

import csv
with open('test') as f:
    for row in csv.reader(f):
        for item in row:
            item=item.strip('{} "')
            print(item)

The strip method removes the specified characters from the left or right end of the string item.

Upvotes: 1

Tim McNamara
Tim McNamara

Reputation: 18385

You will need to look into csv.writer to export data to csv, rather than csv.reader.

EDIT: The body and title of question conflict. You're right about using csv.reader.You can use print in a for loop to achieve the result you are after.

Upvotes: 0

Related Questions