-5

I'm looking for some advice on how to split CSV file using Python. I'm new to Python and strugling with finding the easiest way to achieve it.

Here is the simple example that data I'm trying to split:

ID tags
01 tag1;tag2;tag3;

and here is what I would like data to be presented after:

ID tags
01 tag1
01 tag2
01 tag3

Remark here is that column "tags" can hold the unlimited number of values.

Any advice will be much appreciated.

Thanks

Here is what worked for me. Thanks for the tips.


with open("test.csv", "r") as f:
    for line in f:
        l = line.split(',')
        tags = l[1].split(';')
        for t in tags: 
            print(l[0],t.strip())
4
  • 3
    Please show the actual formatting of the CSV file. Commented Feb 18, 2021 at 18:09
  • Does this answer your question? Python import csv to list Please note that asking on Stack Overflow is not a substitute for doing your own research. Commented Feb 18, 2021 at 18:09
  • 1
    Have you tried using the str.split method with ';' as argument? Do you know already how to read a CSV file, or what exactly is the difficulty? Commented Feb 18, 2021 at 18:10
  • Hi, thanks for the tips, I've had part that opened file and read the context of it. I only could display the desired output. I've used the following and it worked: with open("test.csv", "r") as f: for line in f: l = line.split(',') tags = l[1].split(';') for t in tags: print(l[0],t.strip()) Commented Feb 18, 2021 at 18:36

1 Answer 1

2

Well, the most straightforward approach would be (no libraries), to just do

new_data = []

with open("data.csv", "r") as f:
    # f.readline() if the csv has a header (skips first line)
    for line in f:
        split_kv = line.split(',')
        split_v = split_kv[1].split(';')
        for v in split_v:
            new_data.append((split_kv[0], v))
        
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.