-1

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())
desertnaut
  • 57,590
  • 26
  • 140
  • 166
JPM
  • 11
  • 1
    Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – natka_m Oct 12 '22 at 16:01
  • Or maybe this one? [Creating a dictionary from a CSV file](https://stackoverflow.com/questions/14091387/creating-a-dictionary-from-a-csv-file) – natka_m Oct 12 '22 at 16:03

2 Answers2

0

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 $
floupinette
  • 150
  • 11
0

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
Arifa Chan
  • 947
  • 2
  • 6
  • 23