I want to delete rows from line 2 to a specific numbers in CSV f

ghz 15hours ago ⋅ 5 views

I want to delete rows from line 2 to a specific numbers in CSV file, but it deletes all from the file

Currently, It is deleting everything in CSV, also How can I make a default number so, It will delete from line 2nd to a specific row.

This is what I'm doing

import csv

user_input = input("Please enter a row name to be deleted.")
read = open('color.csv', 'rb')
write = open('color.csv', 'wb')
writer = csv.writer(write)

for row in csv.reader(user_input):

    if row == input:
        writer.writerow(row)
        read.close()
        write.close()
        
print('Used colors names deleted')

Answer

Your code has several issues:

  1. It opens the same file (color.csv) for both reading and writing simultaneously, which will erase the file contents.
  2. The logic for comparing the row to delete (if row == input) is incorrect. It compares the entire row object to the user input instead of checking specific values.
  3. The file operations are not using a proper context manager (with statement), which may lead to file corruption or unclosed files.
  4. The code doesn't handle deleting rows from a specific line number to another.

Fixed Code

Here's a revised implementation that:

  1. Deletes rows from the second row up to a specific row number.
  2. Uses a default range if no input is provided.
import csv

# Open the file for reading and writing
filename = 'color.csv'

# Specify default range
default_start = 2
default_end = 5

# Get user input
try:
    user_input_start = input(f"Enter the starting row to delete (default {default_start}): ")
    user_input_end = input(f"Enter the ending row to delete (default {default_end}): ")

    start_row = int(user_input_start) if user_input_start else default_start
    end_row = int(user_input_end) if user_input_end else default_end
except ValueError:
    print("Invalid input. Using default range.")
    start_row = default_start
    end_row = default_end

# Read the CSV and filter rows
with open(filename, 'r') as read_file:
    rows = list(csv.reader(read_file))

# Write the filtered rows back to the file
with open(filename, 'w', newline='') as write_file:
    writer = csv.writer(write_file)
    for i, row in enumerate(rows, start=1):
        # Skip rows within the range to delete
        if start_row <= i <= end_row:
            continue
        writer.writerow(row)

print(f"Rows from {start_row} to {end_row} have been deleted.")

Explanation

  1. User Input Handling:

    • The script prompts the user to input the starting and ending rows for deletion. If no input is provided, default values are used.
  2. Reading and Writing:

    • The csv.reader reads the rows into a list.
    • After processing, the rows are rewritten using csv.writer without modifying the file during the read operation.
  3. Row Filtering:

    • The script skips rows within the specified range while rewriting the file.
  4. Context Managers:

    • Files are opened using with, which ensures proper cleanup (file closure) even in case of errors.

Example File

Input color.csv:

Name,Color
Apple,Red
Banana,Yellow
Cherry,Red
Lime,Green
Grape,Purple

Deleting rows 2–4 results in:

Name,Color
Apple,Red
Grape,Purple