Home > Enterprise >  Read in CSV and Capture Values to use for Calculation
Read in CSV and Capture Values to use for Calculation

Time:10-13

I need to read in a csv file line by line and do some calculations. For example, let's say I have a csv file named test.csv with data below. I want to read the file in line by line and calculate profit for each client(revenue-expenses).

client,revenue,expenses
client_a,1000,450
client_b,2000,1200
client_c,1500,350

I've been looking around a lot online and I'm not exactly sure. I can read the file line by line or print the file, but not sure if I need to assign variables for each field. I assume i need to declare them as int since I am doing calculations.

I don't want to use a list.

Here's what i have to read the file in and print it on the screen. I know I need to loop through the file line by line and do the calculation. Struggling with how to call the values from the csv file and how to ignore the first line.

inputfile = open('test.csv', "r")

print(inputfile.readline())

CodePudding user response:

At least, you should use csv library for that.

import csv

with open("input.csv", "r") as file:
    mycsvfile = csv.reader(file, delimiter=",")
    
    for line, content in enumerate(mycsvfile):
        
        if line == 0:
            continue
        
        print("the client number {} is : {}".format(line, content[0]))
        
        print("the client number {} earns : {} $".format(line, content[1]))
        
        print("the client number {} spends {} $".format(line, content[2]))

The output will be

the client number 1 is : client_a
the client number 1 earns : 1000 $
the client number 1 spends 450 $
the client number 2 is : client_b
the client number 2 earns : 2000 $
the client number 2 spends 1200 $
the client number 3 is : client_c
the client number 3 earns : 1500 $
the client number 3 spends 350 $

CodePudding user response:

DictReader from csv module will create dictionary from each line in csv file. It will treat header as keys and line below it as values.

Once assigned, iterate the inputfile and print each pair of dictionary and peform calculation on each value after it casted to integer

from csv import DictReader

inputfile = DictReader(open('test.csv'))
for row in inputfile:
    print(f"{row['client']} profit : {int(row['revenue']) - int(row['expenses'])}")

# client_a profit : 550
# client_b profit : 800
# client_c profit : 1150
  • Related