Python Forum

Full Version: Output on same line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I made a little code to extract some stock quotes. 

open('outputyahoo.txt', 'w').close()
from yahoo_finance import Share
symbolfile = open('symbols.txt')
 
symbolslist = symbolfile.readlines()
 
for symbol in symbolslist:
    stocks = Share(symbol)
    price = stocks.get_price()
    print(symbol +" " + price)
 
    saveFile = open('outputyahoo.txt', 'a')
    saveFile.write((symbol +" " + price)+ '\n')
    saveFile.close()
The output comes like 

Output:
ASFI  7.15 3828.HK  1.19 564.SI  0.88
I would like to output to come as
ASFI 7.15
3828.HK 1.19
etc

Thanks for the help
most likely it is symbol as it is the whole line of the file which would include the newline at the end
>>> '\nblah\n'.strip()
'blah'
So I would try

symbol.strip()
Tnx

I solved it with this line 

symbolslist = symbolfile.read()

symbolslist = symbolslist.split('\n')
Several other issues with your code:
1. line #1 is not necessary. Later on you open the same file in append mode and if the file does not exist, it will be created when accessed for the first time.
2. You open the files, but never close the symbolfile. Anyway it's better to use with context manager, that will take care to close the file for you
3. no need to open the file in the loop and close it with every iteration, better open it outside of the loop, it's more efficient.
4. It's recommended to use format method for string formatting, or even the new f-strings (that's only python 3.6)
5. Although it's perfectly OK to read the entire symbolfile into memory, it's better to iterate over it line by line.


from yahoo_finance import Share
with open('symbols.txt') as symbolfile, open('outputyahoo.txt', 'a') as savefile:
   for symbol in symbolfile:
       symbol = symbol.strip()
       stocks = Share(symbol)
       price = stocks.get_price()
       my_output = '{}: {}\n'.format(symbol, price)
       print(my_otput, end = '')
       savefile.write(my_otput)
(May-03-2017, 11:48 AM)buran Wrote: [ -> ]Several other issues with your code:

Tnx for pointing out. Makes the learning curve keep going up and to the right