[Tutor] name shortening in a csv module output

Jim Mooney cybervigilante at gmail.com
Thu Apr 23 07:18:31 CEST 2015


I'm trying the csv module. It all went well until I tried shortening a long
first name I put in just to exercise things. It didn't shorten. And I also
got weird first characters on the header line. What went wrong?

import csv
allcsv = []
with open('data.txt') as csvfile:
    readCSV = csv.reader(csvfile, delimiter='|')
    topline = next(readCSV)
    topline[0] = topline[0].replace('_', ' ').title()
    topline[1] = topline[1].replace('_', ' ').title()
    print("{0:<20s} {1:<20s}".format(topline[0], topline[1]))
    print('==================================')
    for line in readCSV:
        if len(line[0]) > 40:  # problem here - didn't shorten
            line[0] = line[0][:40]
        print("{0:<20s} {1:<20s}".format(line[0], line[1]))

Original file lines:

first_name|last_name|email|city|state or region|address|zip
Stewartrewqrhjeiwqhreqwhreowpqhrueqwphruepqhruepqwhruepwhqupr|Dorsey|nec.malesuada at Quisqueporttitoreros.com|Cariboo
Regional District|BC|P.O. Box 292, 8945 Nulla Avenue|5945
Madonna|Sosa|senectus.et at eget.ca|Belford Roxo|Rio de Janeiro|P.O. Box 538,
4484 Sem Avenue|81833
Duncan|Hutchinson|Donec.vitae at Integer.co.uk|Dublin|Leinster|Ap #847-2344
Feugiat. St.|9222
...

My result:

Ï»¿First Name        Last Name           # odd characters on header line
==================================
Stewartrewqrhjeiwqhreqwhreowpqhrueqwphru Dorsey
Madonna              Sosa
Duncan               Hutchinson
...




-- 
Jim

No comment


More information about the Tutor mailing list