Select row to be deleted in csv file in python -


this maybe basic question, let's suppose 1 has csv file looks follows:

a,a,a,a b,b,b,b c,c,c,c d,d,d,d e,e,e,e 

and interested in deleting row[1], , row[3] , rewrite new file not contain such rows. best way this?. module csv loaded in code, i'd know how within such scheme. i'd glad if me this.

since each row on separate line (assuming there no newlines within data items of rows themselves), can copying file line-by-line , skipping don't want kept. since i'm unsure whether number rows starting 0 or one, i've added symbolic constant @ beginning control it. could, of course, hardcode it, rows_to_delete, directly code.

regardless, approach faster using, example, csv module, because avoids unnecessarily parsing , reformatting of data being processed module has do.

first_row_num = 1  # or 0 rows_to_delete = {1, 3}  open('infile.csv', 'rt') infile, open('outfile.csv', 'wt') outfile:     outfile.writelines(row row_num, row in enumerate(infile, first_row_num)                         if row_num not in rows_to_delete) 

resulting output file's contents:

b,b,b,b d,d,d,d e,e,e,e 

Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -