Home > Blockchain >  Remove rows from .csv file using python
Remove rows from .csv file using python

Time:01-05

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

CodePudding user response:

import pandas as pd
df = pd.read_csv("dataset1.csv",skiprows=4)
df.to_csv("new_csv.csv",index=False)

CodePudding user response:

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)
  •  Tags:  
  • Related