0

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']
1
  • 1
    The csv reader will assume your values are separated by commas if you do not tell it different. So the reader gives you a row with 2222;a 0 as the first element; and then you split it by ; subsequently. If you want to manually split each line, there is no need to use csv.reader. Commented Dec 29, 2020 at 23:54

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

You could just use split() on its own. This is some code that should work (untested), assuming csv is the raw string data:

C = csv.split("\n")
Y = []
for X in C:
    Y.append(X.split(";"))

2 Comments

Better to use the csv module correctly, as it properly handles columns that contain the delimiter.
Sorry I really don't know much about this, am using my phone and it's 00:08 where I live. Please feel free to downvote and ignore this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.