How to delete a row of CSV file using csv reader in Python?
I want to process each row of a csv file and store into database. After that row is stored I want to delete that row in the csv file. I have written code for fetching and storing the row. But I got stuck on deleting a row on csv file.
My code:
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 = col开发者_开发百科s1[2]
contact.phoneno = cols1[3]
#names.append(data[0])
contact.save()
- Read the CSV into memory e.g. a list.
- Save the relevant rows to the database and remove them from the list.
- Save the remaining rows in the list back to the CSV file.
I propose you this code
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
If all the file is treated, you don't care of deleting the rows while processing: you will delete the file after the treatment.
If you want to delete some rows on the basis of precise conditions, say it and we will adapt the above code
精彩评论