-3
f = urlopen ('http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=4&e=29&f=2014&g=d&a=8&b=22&c=1981&ignore=.csv')
sys.stdout = open('output.csv', 'w')
p = f.read()
print p
f.close

This successfully opens (or creates) a file called output.csv and outputs the lines from the downloaded file into this local csv. How would I reverse the order that the lines are printed in?

Apollo
  • 8,874
  • 32
  • 104
  • 192

2 Answers2

5

You can use the readlines() method to get a list of lines instead of the single string you get from read(). This list can be reversed using the reversed() built-in:

for line in reversed(f.readlines()):
    print line
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
3

If there is a header in the input, you might want to print the header first; followed by the remaining lines.

f = urlopen ('http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=4&e=29&f=2014&g=d&a=8&b=22&c=1981&ignore=.csv')
with open('output.csv', 'w') as out:
    # print header first
    out.write(f.readline())

    # then print reversed lines
    for line in reversed(f.readlines()):
        out.write(line)

f.close()  # !!!