Home > Blockchain >  How to read a csv file and convert commas from the numbers to dot?
How to read a csv file and convert commas from the numbers to dot?

Time:11-17

I have written this code to read a csv file :

    for file_to_open in filename:
        file_path = os.path.realpath(file_to_open)
        path_corrected = file_path.replace("file_mngt", "data")
        opened = open(path_corrected)
        reader = csv.reader(opened, delimiter = ";")
        header = next(reader)
        
        for row in reader:
           print(row)

And the result is (for every row) something like this:

['8', 'Thorgal', '8,49', '3', '25,47']

I would like to convert every comma intro a dot, in every single row. I looked on the internet but they all say I have to put "decimal = ',' " in the csv.reader and it doesn't work. Please help. Thanks.

CodePudding user response:

Use a list comprehension and call replace() on each element of the list.

print([item.replace(',', '.') for item in row])

CodePudding user response:

You could pandas if you intend to work further with the data:

import pandas as pd
df = pd.read_csv("your/file/path", delimiter=";", decimal=",")

  • Related