Reputation: 3
I would like to make the first row in csv file as the field name in Django. Is it possible? I would like to read the csv file row by row.
It's my code.
if request.FILES:
form = SalaryForm(request.POST, request.FILES)
if form.is_valid():
# request.session['salary'] = request.POST["salary"]
# salary = Salary.object.get(id=request.session['salary'])
print(request.FILES['fileUpload'].name)
csvfile = request.FILES['fileUpload'].read()
encoding = chardet.detect(csvfile)['encoding']
print (encoding)
if encoding is None:
encoding = 'CP932'
if encoding !='utf-8':
csvfile = csvfile.decode(encoding, 'replace').encode('utf-8')
reader = csv.reader(csvfile, delimiter=',')
but now I the reader can only store Alphabet cannot store words. my CSV file is like this:
'registration_number', 'name', 'kana', 'month', 'day', 'client_code', 'row', 'business_days', 'working_days', 'count', 'early_late_time', 'normal_time', 'over_time', 'holiday_time', 'night_time', 'working_time', 'basic_salary', 'regular_attendance', 'reqular_attendace_allowance', 'over_time_ratio', 'holiday_time_ratio', 'night_time_ratio', 'fare_day', 'fare', 'employment_insurance', 'personally', 'spouse', 'dependent', 'special_allowance', 'adjustment', 'income_tax', 'advanced_payment', 'suspense_payment', 'health_insurance', 'employment_pension', 'employment_insurance_amount', 'no_payment' "223","山野 薫","ヤマノ カオリ",1,10,"1101",1,17,16,,\1,,,,,\8,800,350,0,\1,\1,\0,,8300,1,0,9,0,9200,,2260,,,9557,15928,818,0 "018","波多野 未樹","ハタノ ミキ",1,15,"2301",1,21,20,,,,,,,\8,800,200,0,\1,\1,\0,300,6000,0,,,,,,3360,,,,,,0
I would like to use the first row as my field name, since every time the uploaded files got different format.
thanks very much!
Upvotes: 0
Views: 802
Reputation: 7889
Use csv.DictReader instead of csv.reader
. With the fieldnames
parameter omitted, the first row of the file will be used to determine field names.
Upvotes: 1