-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())
Vlad
  • 119
  • 8
  • 3
    Please show the actual formatting of the CSV file. – mkrieger1 Feb 18 '21 at 18:09
  • Does this answer your question? [Python import csv to list](https://stackoverflow.com/questions/24662571/python-import-csv-to-list) Please note that [asking on Stack Overflow is not a substitute for doing your own research.](//meta.stackoverflow.com/a/261593/843953) – Pranav Hosangadi Feb 18 '21 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? – mkrieger1 Feb 18 '21 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()) – Vlad Feb 18 '21 at 18:36

1 Answers1

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))
        
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28