简体   繁体   English

Python-将多个列表写入文件

[英]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. 这是因为out_quotes变量被第一个循环的每次迭代覆盖。

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 . 正在修改的同一 out_quotes变量对每个quotequotes

The easiest way would be to do both print ing and write ing in the same for loop, like so: 最简单的方法是在相同的for循环中同时进行printwrite ,如下所示:

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: 另外,为简化write行,您可以将其更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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