简体   繁体   中英

Remove row from CSV file python

Is there a way to remove a row from a CSV file without rewriting then entire thing?

Currently, I am using a dictionary 'db' that contains the database with the row I want to delete, first I read the columns, then a completely rewrite every row in the CSV besides for the row with the ID I want to delete, is there a way to do this without having to rewrite everything?

 def remove_from_csv(file_name, id, db):
        with open(file_name, "r") as f:
            reader = csv.reader(f)
            i = next(reader)

        with open(file_name, 'w') as f:
            writer = csv.writer(f, lineterminator='\n')
            writer.writerow(i)
            for i in db:
                if id != i:
                    for j in db[i]:
                        writer.writerow([i, j, db[i][j]])

A way I have done so in the past is to use a pandas dataframe and the drop function based on the row index or label.

For example:

import pandas as pd
df = pd.read_csv('yourFile.csv')
newDf = df.drop('rowLabel')

or by index position:

newDf =df.drop(df.index[indexNumber])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM