Thursday, October 4, 2012

test_csv_helpers.py


test_csv_helpers.py





import unicodecsv
from cStringIO import StringIO

line = "The quick brown fox, JUMPS OVER, the lazy dog."

# 1
##csv_line_f = None
##csv_reader = None
##try:
##    csv_line_f = StringIO(line.encode('utf-8'))
##
##    csv_reader = unicodecsv.reader(csv_line_f, encoding='utf-8')
##    for i,csv_row in enumerate(csv_reader):
##        if i > 0:
##            assert False, 'More than one csv line read in csv_line_f ?!'
##        print "csv_row=", csv_row
##
##finally:
##    if csv_line_f:
##        csv_line_f.close()
##    if csv_reader:
##        csv_reader.close() # AttributeError: 'UnicodeReader' object has no attribute 'close'

# 1 (CONCLUSION): csv.reader object no need to .close() ; meaningless.
# refer to
# http://stackoverflow.com/questions/3216954/python-no-csv-close



# 2 (CAN'T USE WITH with STRINGIO)
##with StringIO(line.encode('utf-8')) as csv_line_f:      # AttributeError: 'cStringIO.StringI' object has no attribute '__exit__'
##    csv_reader = unicodecsv.reader(csv_line_f, encoding='utf-8')
##    for i,csv_row in enumerate(csv_reader):
##        if i > 0:
##            assert False, 'More than one csv line read in csv_line_f ?!'
##        print "csv_row=", csv_row


# 3 (THE CORRECT IMPLEM)
csv_line_f = None
try:
    csv_line_f = StringIO(line.encode('utf-8'))

    csv_reader = unicodecsv.reader(csv_line_f, encoding='utf-8')
    for i,csv_row in enumerate(csv_reader):
        if i > 0:
            assert False, 'More than one csv line read in csv_line_f ?!'
        print "csv_row=", csv_row

finally:
    if csv_line_f:
        csv_line_f.close()



No comments:

Post a Comment