I want to read a CSV file\'s columns directly into variables. The result should be something like you would get with the following shell line: while IFS=, read ColumnName1
Is this what you were looking for (Python 3.X):
import csv
from io import StringIO
# Simulate a csv data file with no header
data = StringIO('''\
Mark,44,1
Joe,22,0
Craig,39,3
''')
for row in csv.DictReader(data,'Name Age Children'.split()):
print(row)
{'Age': '44', 'Name': 'Mark', 'Children': '1'}
{'Age': '22', 'Name': 'Joe', 'Children': '0'}
{'Age': '39', 'Name': 'Craig', 'Children': '3'}
Or maybe:
import csv
from io import StringIO
# Simulate a csv data file with no header
data = StringIO('''\
Mark,44,1
Joe,22,0
Craig,39,3
''')
# 1. Read in all the data
# 2. Transpose into columns
# 3. Match with column names
# 4. Create dictionary
cols = dict(zip('Name Age Children'.split(),zip(*csv.reader(data))))
print(cols)
{'Age': ('44', '22', '39'), 'Name': ('Mark', 'Joe', 'Craig'), 'Children': ('1', '0', '3')}