0

I'm doing a python script that reads a CSV file. This is the code:

with open("DATABASE.csv", "r", newline="") as a:
    csv_reader = csv.DictReader(a)
    rows = list(csv_reader)
    print(rows[2]["NAME"] rows[2]["SURNAME"])

The [2] means that it read the second line of the file.

How can I replace it with a number chosen by the user? If I save the user's choice into a variable and I insert the variable in the [ ] it reply with TypeError: list indices must be integers or slices, not str

--

And other little thing: is there a way to delete a single line in the CSV?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
enricozz
  • 9
  • 1
  • 3
  • _"is there a way to delete a single line in the CSV"_: Read the whole CSV to a list, remove the row you want to from your list, and write all rows back to the file. See [this question](https://stackoverflow.com/questions/56987312/how-to-delete-only-one-row-in-csv-with-python). Also read [How much research effort is expected of Stack Overflow users?](//meta.stackoverflow.com/a/261593/843953) The answers you seek already exist on Stack Overflow, and [google is your friend](https://www.google.com/search?q=is+there+a+way+to+delete+a+single+line+in+the+CSV) – Pranav Hosangadi Jul 19 '22 at 14:55

1 Answers1

-1

input() return a string, so you have to cast it to integer, change the input code with int(input()).

If you want to delete a single line on the csv file just modify the list that contains the csv file, in your case the rows variable, and then save it back to csv file.

Yusuf Syam
  • 701
  • 1
  • 4
  • 18
  • Thanks! Now however it says me that "IndexError: list index out of range", but if I write only the string "print(rows[1]["NAME"]....) it works. – enricozz Jul 19 '22 at 15:06
  • Nice! if this help you i would appreciate if you upvote this answer :) – Yusuf Syam Jul 19 '22 at 15:23