1

I need to move these three lists of data to a tab-delimited text file. I only know how to print them consecutively (as I have done below).

import requests
import datetime as dt
import xmltodict
url='http://forecast.weather.gov/MapClick.php?lat=47.6062&lon=-122.3321&FcstType=digitalDWML'
r = requests.get(url)

with open('KBFI_2.txt','wb') as outfile:
    result = xmltodict.parse(r.text)
    pop = result['dwml']['data']['parameters']['probability-of-precipitation']['value']
    pop = '\n'.join(pop)
    hqpf = result['dwml']['data']['parameters']['hourly-qpf']['value']
    hqpf = '\n'.join(hqpf)
    d = result['dwml']['data']['time-layout']['start-valid-time']
    for dte in d:
        date = dt.datetime.strptime(dte.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S")
        print >>outfile, date
    print >>outfile, pop
    print >>outfile, hqpf
    outfile.close()

I'm sure this is a really easy fix, but I'm a newbie so I'm lost. All help is appreciated!

1
  • 2
    You don't need to outfile.close(), as that is handled automatically by the with statement. Commented Aug 3, 2015 at 18:51

1 Answer 1

2

You seem to know how to combine things into multiple lines in one string ('\n'.join); to make lines tab-delimited, use '\t'.join for each line.

The other piece is to take your 3 lists and turn them into a list of triplets, so that you can use join to make each triplet into a tab-delimited line. Something like this:

for a,b,c in zip(list1, list2, list3):
    print >>outfile, "\t".join([a,b,c])

Finally, you can make a list of your dates using:

[dt.datetime.strptime(x.rsplit("-",1)[0],"%Y-%m-%dT%H:%M:%S") for x in dte]
Sign up to request clarification or add additional context in comments.

4 Comments

Isn't this just how you make one list tab delimited? I need to print my three lists so I have a column of dates, a column of 'pop' and a column of 'hqpf'. I'm not sure how to do this with '\t'.join
This does not work, I get the error TypeError: zip argument #1 must support iteration. I think this is happening because the value of 'date' changes when it exits its loop. Also, if I just complete your answer using 'pop' and 'hqpf', the data looks all funky in the output file. If you would like to see for yourself, you should be able to run my code because my xml doc is online.
They have to be lists: don't join pop or hqpf (that gets done in the zip loop), and collect your dates into a list. And tab-separated files are allowed to look "funky".
Oh I see. I can make it work with pop and hqpf now. However, I'm having trouble converting date to a list. When I ask Python what Type it is, it gives me <type 'type'> and I'm not sure how to work with this. Can you shed a little light on it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.