I have a CSV that is semicolon separated, and that uses double quotes as a quote character. I get this CSV from an API, the raw data looks like this :
1;"toto@toto.com";"Toto";"Tata"
2;"BAD_DATA"
"BAD_DATA"
3;"alice@alice;com";"Alice";"Dupont"
4;"bob@bob.fr";"Bob";"Morane"
The second and third lines are like this because of encoding problems at the source, I cannot change this.
I would like to change the string to this :
1;"toto@toto.com";"Toto";"Tata"
3;"alice@alice;com";"Alice";"Dupont"
4;"bob@bob.fr";"Bob";"Morane"
So that all the lines with the wrong length are deleted. But since my code will run on a server, I would like if possible to do all of this in memory, without writing to a file on the machine.
As you can see, some of the fields can contain semicolons so I need to protect those with double quotes around them. It adds a little complexity.
So far, I have this :
import csv
myString = f'''1;"toto@toto.com";"Toto";"Tata"
2;"BAD_DATA"
"BAD_DATA"
3;"alice@alice;com";"Alice";"Dupont"
4;"bob@bob.fr";"Bob";"Morane"'''
lines = myString.splitlines()
reader = csv.reader(lines, delimiter=';', quotechar='"')
for row in reader:
if len(row) == 4:
# I don't know what to do here
I anybodys knows in what direction I can try to advance, that would be very nice :)