Values ​on one line each after the decimal point. CSV with Python 3+

Viewed 29

I have a CSV file whose structure looks something like this:

Name    Nation  Location    URL
Electra European    Luton, Dunstable, Stevenage //ur1l/, //url2/, //url3/
Bob British Bedford, Bedfordshire   //ur1l/, //url21/, //url13/
Lyndi   Thai    Liverpool Street, Street, Goodge Street //ur11l/, //url12/, //url3/

enter image description here

I am trying to access each link separately, but my attempts return each letter separately:

My code:

with open('csv/users.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)
    for line in csv_reader:
        print(line) #ok
        for link in line[3]:
            print(link) # it's return each letter separately

How do you get each link separately?

1 Answers

The fields in the file are separated by tabs, and multiple values by ', ' so I doubt that even line or line[3] contain the values you expect.

You should handle the file accordingly:

with open('csv/users.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter='\t')
    next(csv_reader)
    for line in csv_reader:
        for link in line[3].split(', '):
            print(link)

BTW, instead of skipping the header row with next(csv_reader) and then using unreadable line[3], you can use DictReader to be able to access columns by name:

import csv

with open('csv/users.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter='\t')
    for line in csv_reader:
        for link in line['URL'].split(', '):
            print(link)
Related