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]);
quoting
- csv.QUOTE_ALL, quote all fields
- csv.QUOTE_MINIMAL, quote those fields which contain special characters such as delimiter, quotechar or any of the characters in lineterminator
- csv.QUOTE_NONNUMERIC, quote all non-numeric fields
#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);
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'})
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()
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)