Skip to content
Advertisement

Split string with unexpected behaviour?

I am reading a csv file and I use a split on every line but I do not fully understand the behavior.

csv file:

id;name;number
1111;foo nbar;2.00
2222;a 0,25;1.00

code:

for file in csvs:
    with open(file, encoding = "utf8") as f:
        reader = csv.reader(f)
        for row in reader:
            if isinstance(row, str):
                print(row)
            else:
                print(row[0].split(";"))

This yields:

['number', 'name', 'price']
['1111', 'foo \nbar', '2.00']
['2222', 'a 0']

but I expected the last line to be:

['2222', 'a 0,25', '1.00']

Advertisement

Answer

Use the delimiter arg to csv.reader to split on semicolons instead of commas:

for file in csvs:
    with open(file, encoding = "utf8") as f:
        reader = csv.reader(f,delimiter=";")
        for row in reader:
            print(row)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement