-2

I want to replace all character(',') with character ('.')

I try with this code :

spamReader = csv.DictReader(base64.b64decode(self.file_name).decode('utf-8').split('\n'), delimiter=';')
    for row in reversed(list(spamReader)):
         for k, v in row.items():
         row[k] = k.replace(',', '.') 

But , does not work . Any help please ?

Ing
  • 551
  • 7
  • 20
  • 1
    Is your code formatted as you show it in the question? – 0buz Mar 11 '20 at 16:37
  • "Does not work" does not provide enough information. – Jongware Mar 11 '20 at 17:55
  • Welcome to StackOverflow. Why are you using DictReader? – Mehdi Haghgoo Mar 11 '20 at 17:57
  • Please supply the expected [minimal, reproducible example(https://stackoverflow.com/help/minimal-reproducible-example) Your posted code fails on a syntax errror in the last line, and then fails for undefined variables. Replace the first line with a simple, hard-coded sample of your data structure. Add `print` statements to display the result. – Prune Mar 11 '20 at 17:57

2 Answers2

1

I see two things here:

  1. Your base64 encoding part for the file reference looks a bit strange to me, but if it opens correctly, it shouldn't be the issue here, I guess.

  2. You are modifying an object you are iterating over at the same time. I think you should avoid that, since it might lead to strange behaviour, if it works at all. (Modifying a Python dict while iterating over it). It might be a better idea, to simply store your data in a new object.

I tried to fix both in this code and since I am unsure what data structure fits best for your further program, chose something that you should be able to use pretty similar to the OrderedDict that was returned by DictReader:

new_data = []
with open('test.csv') as file:
    reader = csv.DictReader(file, delimiter=';')
    for row in reader:
        new_row = []
        for key in row:
            entry = (key, row[key].replace(',','.'))
            new_row.append(entry)
        new_data.append(new_row)

Hope that helps! :)

SurfChriz
  • 57
  • 5
0

I think your last line isn't indented properly - it needs 4 more spaces.

Also, I think you're replacing row[k] with a modified k; you may have intended row[k] to be replaced with a modified v.

dstromberg
  • 6,954
  • 1
  • 26
  • 27