我想处理csv文件的每一行并存储到数据库中。存储该行后,我想删除csv文件中的该行。我已经编写了用于获取和存储行的代码。但是我在csv文件上删除了一行。
我的代码:
import csv
entries = csv.reader(open('/opt/workspace/jup/juppro/media/docs/phonebook.csv', 'rb'), dialect='excel-tab')
entries_list = []
entries_list.extend(entries)
total_records= len(entries_list)
uploaded_records=0
for data in entries_list:
uploaded_records=uploaded_records+1
cols = data[0].replace('"','')
cols1= cols.split(';')
contact = phonebook()
contact.email = cols1[0]
contact.firstname = cols1[1]
contact.lastname = cols1[2]
contact.phoneno = cols1[3]
#names.append(data[0])
contact.save()
答案 0 :(得分:1)
答案 1 :(得分:0)
我建议你这个代码
import csv
from os.path import getsize
from itertools import islice
print 'size of file :',getsize('/opt/workspace/jup/juppro/media/docs/phonebook.csv')
entries = csv.reader(open('/opt/workspace/jup/juppro/media/docs/phonebook.csv', 'rb'), dialect='excel-tab')
n = 3
cnt = 0
chunk = True
while chunk:
chunk = list(islice(entries,n))
if chunk==[]:
print 'processing ended'
break
# here: all the treatments of the rows being in chunk
cnt += n
print cnt
如果处理完所有文件,则无需在处理时删除行:您将在处理后删除该文件。
如果你想根据精确的条件删除一些行,请说出来,我们将调整上面的代码