2

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

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.