简体   繁体   中英

Python - Write multiple lists to file

I'm writing stock ticker program that will display the result onto the screen and also write it to file. I had no problem with display the result onto the screen, but the result in the file was not what I expected.

Code to display the result to the screen:

tickerList = ticker.split() 
quotes = get_stock_quote(tickerList)
for quote in quotes:
    print 'ticker: %s' % quote['t'], 'current price: %s' %    quote['l_cur'], 'last trade: %s' % quote['lt'] 

Result (as I expected):

ticker: AAPL current price: 111.31 last trade: Oct 6, 4:00PM EDT
ticker: GOOG current price: 645.44 last trade: Oct 6, 4:00PM EDT
ticker: IBM current price: 148.80 last trade: Oct 6, 6:20PM EDT

Code to write to file:

for quote in quotes:
    out_quotes = ['ticker: %s ' % quote['t'], 'current price: %s ' % quote['l_cur'], 'last trade: %s ' % quote['lt']]

outfile = open('result.txt', 'w')
for quote in out_quotes:
    outfile.writelines(chain(*out_quotes))
    outfile.write('\n')

Result :

ticker: IBM current price: 148.80 last trade: Oct 6, 6:20PM EDT 
ticker: IBM current price: 148.80 last trade: Oct 6, 6:20PM EDT 
ticker: IBM current price: 148.80 last trade: Oct 6, 6:20PM EDT 

I was expecting the same result as the one displayed onto the screen. Anyone can help to point out my mistake? Thanks in advance.

It's because the out_quotes variable get overwritten by each iteration of the first loop.

You should open the file before the first loop and write to the file directly inside the first loop (and have no second loop).

You are modifying the same out_quotes variable for every quote in quotes .

The easiest way would be to do both print ing and write ing in the same for loop, like so:

for quote in quotes:
    print 'ticker: %s' % quote['t'], 'current price: %s' %    quote['l_cur'], 'last trade: %s' % quote['lt']
    outfile.write(''.join(['ticker: %s ' % quote['t'], 'current price: %s ' % quote['l_cur'], 'last trade: %s ' % quote['lt']]) + '\n')

Also, to simplify the write line, you could change it to this:

outfile.write('ticker: %s current price: %s last trade: %s\n' % (quote['t'], quote['l_cur'], quote['lt']))

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