Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV Import with Python - Why brackets?

Tags:

python

csv

I'm writing a script that will import a list of urls from a CSV, then loop through the URLs for a response. When I import the CSV, each site is enclosed in brackets and single-quotes.

My csv looks like this:

http://cnn.com
http://yahoo.com
http://google.com

The name of the csv is sites.csv.

Here is the code I'm running:

import csv

datafile = open('path/to/file/sites.csv', 'rU')
datareader = csv.reader(datafile)
for row in datareader:
    print row

Here is the output:

['http://cnn.com']
['http://yahoo.com']
['http://google.com']

Is there a way to not include the [','] around the URL when reading the CSV? If there is not, then is my solution to strip out the [','] in my loop, then access the URL?

like image 231
mikebmassey Avatar asked Dec 22 '25 17:12

mikebmassey


1 Answers

Each row consists of a python list of columns, with only one column in this case.

Since there are no comma-separated columns, just one item per line, you don't need to use the csv module here. Just read from the file directly:

with open('path/to/file/sites.csv', 'rU') as datafile:
    for line in datafile:
        print line.strip()
like image 194
Martijn Pieters Avatar answered Dec 24 '25 07:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!