使用 python 从 .csv 文件中删除行

Remove rows from .csv file using python

我将此数据保存在 .csv 文件中,我想从我的 csv 文件中删除前 4 行,然后使用 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
    

使用此代码并出现错误:

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
import pandas as pd
df = pd.read_csv("dataset1.csv",skiprows=4)
df.to_csv("new_csv.csv",index=False)

您也可以这样做:

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)