Home > Mobile >  Deleting a row from a CSV based on line number and shifting all lines afterwards
Deleting a row from a CSV based on line number and shifting all lines afterwards

Time:08-11

Let's say I have this CSV:

my friend hello, test
ok, no
whatever, test
test test, ok

I want to delete line number 3, so I would call my function:

remove_from_csv(3)

I couldn't find any built-in remove function and I don't want to "write" anything, so I'm trying to find a way to just read, remove and shift.

So far, I can at least read the desired line number.

def remove_from_csv(index):

    with open('queue.csv') as file:
        reader = csv.reader(file)

        line_num = 0
        for row in reader:
            line_num  = 1
            if line_num == index:
                print(row)

remove_from_csv(3)

whatever, test

However, I don't know how I could go about just removing that line and doing it without leaving a blank space afterwards.

CodePudding user response:

Try:

import pandas as pd
def remove_nth_line_csv(file_name, n):
    df = pd.read_csv(file_name, header=None)
    df.drop(df.index[n], inplace=True)
    df.to_csv(file_name, index=False, header=False)

Remember pandas indexes from 0. Therefore, counting starts 0,1,2,3,4...n

CodePudding user response:

You could simply try:

from pathlib import Path

with open("queue.csv", "r") as fin, open("new_queue.csv", "w") as fout:
    fout.writelines(line for n, line in enumerate(fin, start=1) if n != 3)
Path("new_queue.csv").rename("queue.csv")

CodePudding user response:

with open('queue.csv',newline='') as file:

use this newline='' while writing the csv file

  • Related