Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove rows from .csv file using python

I have this data in a .csv file and I want to remove 1st 4 rows from my csv file and just save rest of the file in my dataset using python!

import csv
with open('dataset1.csv','rb') as inp, open('dataset-1copy.csv','wb') as out:
    i = 0
    for line in inp:
        if i >= 4:
            print(line)
            csv.writer(out).writerows()
        i+= 1
    

using this code and getting error:

Error                                     Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14912/736960677.py in <module>
      4         if i >= 5:
      5             print(line)
----> 6             csv.writer(out).writerows(line)
      7         i+= 1
      8 

Error: iterable expected, not int

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can also do this:

lines = list()
remove= [1,2,3,4]

with open('dataset1.csv', 'r') as read_file:
    reader = csv.reader(read_file)
    for row_number, row in enumerate(reader, start=1):
        if(row_number not in remove):
            lines.append(row)

with open('new_csv.csv', 'w') as write_file:
    writer = csv.writer(write_file)
    writer.writerows(lines)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading