Graphics Programs Reference
In-Depth Information
<date>20090104</date>
<max_temperature>34</max_temperature>
</observation>
...
</weather_data>
each day's temperature is enclosed in <observation> tags with a <date> and
the <max_temperature> .
To convert the CSV into the preceding XML format, you can use the follow-
ing code snippet:
import csv
reader = csv.reader(open('wunder-data.txt', 'r'), delimiter=”,”)
print '<weather_data>'
for row in reader:
print '<observation>'
print '<date>' + row[0] + '</date>'
print '<max_temperature>' + row[1] + '</max_temperature>'
print '</observation>'
print '</weather_data>'
As before, you import the necessary modules. You need only the csv mod-
ule in this case to read in wunder-data.txt .
import csv
The second line of code opens wunder-data.txt to read using open() and
then reads it with the csv.reader() method.
reader = csv.reader(open('wunder-data.txt', 'r'), delimiter=”,”)
Notice the delimiter is specified as a comma. If the file were a tab-
delimited file, you could specify the delimiter as '\t' .
Then you can print the opening line of the XML file in line 3.
print '<weather_data>'
In the main chunk of the code, you can loop through each row of data and
print in the format that you need the XML to be in. In this example, each
row in the CSV header is equivalent to each observation in the XML.
for row in reader:
print '<observation>'
Search WWH ::




Custom Search