csv
Writer
import csv

array = [['Hello', 'World'], ['Lin', 'Yanhua']]

with open('eggs.csv', 'w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerow(array[0]);
    spamwriter.writerow(array[1]);
		
Write Special Characters
  • quoting
  • #writerow
    import csv
    
    array = [['Hello', 'World'], ["Lin's, Name", 'Yanhua"s, Name']]
    
    with open('eggs.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerow(array[0]);
        spamwriter.writerow(array[1])
    		
    #eggs.csv
    #Hello,World
    #"Lin's, Name","Yanhua""s, Name"
    		
    #writerows
    import csv
    
    array = [['Hello', 'World'], ["Lin's, Name", 'Yanhua"s, Name']]
    
    with open('eggs.csv', 'w') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        spamwriter.writerows(array);
    		
    DictWriter
    import csv
    
    with open('names.csv', 'w', newline='') as csvfile:
        fieldnames = ['first_name', 'last_name']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        writer.writerow({'first_name': "Baked's, Name", 'last_name': 'Beans'})
        writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
        writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
    		
    Reader
    import csv
    
    with open('eggs.csv', newline='') as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
        for row in spamreader:
            for field in row:
                print(field, end='|')
            print()
    		
    Dialects
  • excel, Microsoft Excel and LibreOffice
  • unix, quotes all fields with double-quotes and uses \n as the record separator
  • import csv
    
    print(csv.list_dialects()) #complete list of registered dialects
    dialet = csv.get_dialect('excel')
    
    print('|'+dialet.delimiter+'|')
    print('|'+str(dialet.doublequote)+'|')
    print('|'+str(dialet.escapechar)+'|')
    print('|'+dialet.lineterminator+'|')
    print('|'+dialet.quotechar+'|')
    print('|'+str(dialet.quoting)+'|')
    print('|'+str(dialet.skipinitialspace)+'|')
    print('|'+str(dialet.strict)+'|')
    		
    import csv
    
    csv.register_dialect('pipes', delimiter=',')
    
    with open('names.csv', 'r') as f:
        reader = csv.reader(f, dialect='pipes')
        for row in reader:
            print(row)
    		
    Reference
  • PYMOTW
  • Python3 Documents