0
def usunPsa(self, ImiePsa):

    with open('schronisko.csv', 'rb') as input, open('schronisko.csv', 'wb') as output:
        writer = csv.writer(output)
        for row in csv.reader(input):
                if row[0] == ImiePsa:
                    writer.writerow(row)
    with open(self.plik, 'r') as f:
            print(f.read())


Dsac;Chart;2;2020-11-04
Dsac;Chart;3;2020-11-04
Dsac;Chart;4;2020-11-04
Lala;Chart;4;2020-11-04
Sda;Chart;4;2020-11-04
Sda;X;4;2020-11-04
Sda;Y;4;2020-11-04
pawel;Y;4;2020-11-04`

If I use usunPsa("pawel") every line gets removed.

Following code earse my whole csv file instead only one line with given ImiePsa, What may be the problem there?

2 Answers2

1

I found the problem. row[0] in your code returns the entire row, that means the lines are not parsed correctly. After a bit of reading, I found that csv.reader has a parammeter called delimiter to sepcify the delimiter between columns.

Adding that parameter solves your problem, but not all problems though. The code that worked for me (just in case you still want to use your original code)

import csv

def usunPsa(ImiePsa):
    with open('asd.csv', 'rb') as input, open('schronisko.csv', 'wb') as output:
        writer = csv.writer(output)
        for row in csv.reader(input, delimiter=';'):
            if row[0] == ImiePsa:
                writer.writerow(row)

usunPsa("pawel")

Notice that I changed the output filename. If you want to keep the filename the same however, you have to use Hamza Malik's answer.

Flashcap
  • 141
  • 2
  • 17
0

Just read the csv file in memory as a list, then edit that list, and then write it back to the csv file.

lines = list()

members= input("Please enter a member's name to be deleted.")

with open('mycsv.csv', 'r') as readFile:

    reader = csv.reader(readFile)

    for row in reader:

        lines.append(row)

        for field in row:

            if field == members:

                lines.remove(row)

with open('mycsv.csv', 'w') as writeFile:

    writer = csv.writer(writeFile)

    writer.writerows(lines)