Python - 将多个列表写入文件(Python - Write multiple lists to file)
我正在编写股票代码程序,它会将结果显示在屏幕上并将其写入文件。 我将结果显示在屏幕上没有问题,但文件中的结果并不符合我的预期。
将结果显示在屏幕上的代码:
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']
结果(如我所料):
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
要写入文件的代码:
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')
结果:
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'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.
原文:https://stackoverflow.com/questions/33004908