0

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.

Trigon
  • 37
  • 5

2 Answers2

1

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

Avi Thaker
  • 455
  • 3
  • 10
  • 1
    Don’t forget to import pandas as pd… oh and install it if it isn’t installed. – Jarvis Aug 11 '22 at 06:48
  • I'm getting weird behavior. Why do I have to do index[n-2] to get the correct line to remove? Also that causes issue if it's line 1 2 because it goes negative or 0. I don't really understand. In your code, it doesn't drop the correct line. – Trigon Aug 11 '22 at 06:52
  • Try your code on my csv file with 4 lines example and try to remove the 2nd line (n = 1). It will remove the 3rd line instead. – Trigon Aug 11 '22 at 06:59
  • But with n-1, if you try to delete line 1, it doesn't work. There's something that's not working well with df.index. – Trigon Aug 11 '22 at 07:09
  • Better read the CSV-file with `header=None`, otherwise the first line is used as column labels. – Timus Aug 11 '22 at 07:14
  • @Trigon if that answers your question, please accept the answer. I have updated it with `header=None` for you. as per @Timus suggestion. – Avi Thaker Aug 11 '22 at 07:32
0

If you're trying to remove a specific line from a file (here the 3.), then you don't need the csv module (or third party libraries), just basic file manipulation should work:

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")
Timus
  • 10,974
  • 5
  • 14
  • 28