简体   繁体   中英

Python - Selecting specific values from CSV web page

import csv
import urllib
url = "https://www.national-lottery.co.uk/player/lotto/results/downloadResultsCSV.ftl"
webpage = urllib.urlopen(url)
datareader = csv.reader((webpage),delimiter=',')

I am trying to select specific values from the CSV file on this URL. However I can't seem to select values from the second row of the file, instead it seems to be giving me just values from the top row, ie Ball 1. Is there a way in Python of selected for instance, the value of '26' from the second row of values?

Just loop over the csv.reader .

with open("downloadResultsCSV.ftl") as i:
    reader = csv.reader(i)
    for row in reader:
        print(row[0]) #  prints the first field of each row

I do get the desired result.

>>> import urllib
>>> url = "https://www.national-lottery.co.uk/player/lotto/results/downloadResultsCSV.ftl"
>>> webpage = urllib.urlopen(url)
datareader = csv.reader((webpage),delimiter=',')
for data in datareader:
  print(data[1])
    ... 
Ball 1
26
46
4

The csv reader object ( datareader in your case) acts like an iterator over rows in the CSV file. The rows it returns can themselves be iterated over to get the individual values in that row.

For instance:

>>> import csv
>>> import urllib
>>> url = "https://www.national-lottery.co.uk/player/lotto/results/downloadResultsCSV.ftl"
>>> webpage = urllib.urlopen(url)
>>> datareader = csv.reader((webpage),delimiter=',')
>>> for row in datareader:
...     print "Row:"
...     for value in row:
...             print "    ", value
...
Row:
     DrawDate
     Ball 1
     Ball 2
     Ball 3
     Ball 4
     Ball 5
     Ball 6
     Bonus Ball
     Ball Set
     Machine
      Raffles
      DrawNumber
Row:
     08-Mar-2014
     26
     2
     9
     44
     12
     31
     5
     5
     LANCELOT

And so on.

Try using a DictReader , since your file has a header:

import urllib
import csv

page = urllib.urlopen(url)
reader = csv.DictReader(page)
rows = list(reader)

for row in rows:
   print(row['Ball 1'])
   print(row['Bonus Ball'])
   # .. etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM