Python – moving final data to a new sheet

Question:

I wrote the following code where when I print it I can see the output/final result of the program, but I want to have my final result as a column in a separate python sheet.

with (open('IBM.csv', newline='', encoding='utf-8') as infile,
          open('IBM_out.csv', 'w', newline='', encoding='utf-8') as outfile):
        reader = csv.DictReader(infile)
        writer = csv.DictWriter(outfile, fieldnames=['Change'])
        writer.writeheader()
        for row in reader:
            row['Close']
            row['Change'] = (float(row['Close']) - float(row['Open'])) / float(row['Open'])

            print(row['Change'])

I want to see the "Change" column in the "IBM_out.csv" file.

Asked By: Mery p.

||

Answers:

Try this and let me if this works for you.

import csv
with (open('IBM.csv', newline='', encoding='utf-8') as infile,
          open('IBM_out.csv', 'w', newline='', encoding='utf-8') as outfile):
        reader = csv.DictReader(infile)
        fieldnames = reader.fieldnames + ['Change']
        writer = csv.DictWriter(outfile, fieldnames=fieldnames)
        writer.writeheader()
        for row in reader:
            row['Close']
            row['Change'] = (float(row['Close']) - float(row['Open'])) / float(row['Open'])

            writer.writerow(row)
Answered By: apan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.