我想从csv文件中检索数据,但我的硬件(RFID)输出为我提供了两个不同的同一员工条目。超时 WorkNames.csv
在这里有双重条目我想在models.py Employee类
中只为一名雇员提供一行所以请在我的METHOD1中提供帮助,建议一些代码可以将2个数据合并为一个,同时将数据转换为sqlite
OR
通过建议从output.csv导入数据的某些代码帮助METHOD2
方法1:我使用 import.py 导入数据。数据导入到sqlite但是双重条目
import os
import sys
import csv
from datetime import datetime
project_dir='catalog'
sys.path.append(project_dir)
os.environ['DJANGO_SETTINGS_MODULE']='locallibrary.settings'
import django
django.setup()
from catalog.models import employee1
data=csv.reader(open('locallibrary/WorkNames.csv'),delimiter=',')
i=1
from datetime import datetime
for row in data:
if row[0]== '':
break
else:
Employee1=employee1()
Employee1.Date=row[0]
Employee1.Name=row[1]
Employee1.Number=row[2]
if row[3] =="" or row[3]=='Time IN':
Employee1.Time_IN='00:00:00 AM'
else:
Employee1.Time_IN=str(row[3])
if row[4] =="" or row[4]=='Time OUT':
Employee1.Time_OUT='00:00:00 AM'
else:
Employee1.Time_OUT=str(row[4])
Employee1.save()
**方法2:但为了在行中获得超时时间,我生成了一个新文件** output.csv
文件已正确生成,但数据未从csv导入到sqlite
import os
import sys
import csv
from datetime import datetime
project_dir='catalog'
sys.path.append(project_dir)
os.environ['DJANGO_SETTINGS_MODULE']='locallibrary.settings'
import django
django.setup()
from catalog.models import employee1
data=csv.reader(open('locallibrary/WorkNames.csv'),delimiter=',')
from datetime import datetime
lines=list(data)
r=5
c=5
for i in range(r):
for j in range(1,5):
if lines[0][j]=="":
break
if lines[i][2] == lines[j][2]:
lines[j][3]=lines[i][3]
r=5
c=5
for i in range(r):
for j in range(1,5):
if lines[i][3]!="" and lines[i][4]=="":
lines[i][3]='00:00:00 AM'
lines[i][4]='00:00:00 AM'
break
writer = csv.writer(open('locallibrary/output.csv', 'w'))
for r in lines:
writer.writerow(r)
open('locallibrary/output.csv').close()
data1=csv.reader(open('locallibrary/WorkNames.csv'),delimiter=',')
i=1
for row in data:
if row['Date']=='':
break
else:
Employee1=employee1()
Employee1.Date=row['Date']
Employee1.Name=row['Name']
Employee1.Number=row['Number']
Employee1.Time_IN=row['Time IN']
Employee1.Time_OUT=row['Time OUT']
Employee1.save()
所以请在我的METHOD1中提供帮助,建议一些代码可以将2个数据合并为一个,同时将数据转换为sqlite
OR
通过建议从output.csv导入数据的某些代码帮助METHOD2
答案 0 :(得分:0)
对方法1的建议
如果您的CSV文件中没有多行(可能少于10.000),那么您可以使用python dict
按员工编号和日期进行分组。
我修改了一小部分代码:
... some code ...
record_dict = {}
for row in data:
if row[0] == '':
break
record_date = row[0]
emp_number = row[2]
key = (emp_number, record_date)
if key not in record_dict:
record_dict[key] = employee1()
record_dict[key].Date = row[0]
record_dict[key].Name = row[1]
record_dict[key].Number = row[2]
record_dict[key].Time_IN = None
record_dict[key].Time_OUT = None
if row[3] not in ('', 'Time IN'):
record_dict[key].Time_IN = row[3]
if row[4] not in ('', 'Time OUT'):
record_dict[key].Time_OUT = row[4]
for emp in record_dict.values():
emp.save()
顺便说一下:你应该阅读PEP8,这是python编码风格指南,显示编写python代码的首选方法。