Python Forum
How do use data from csv files as variables?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do use data from csv files as variables?
#1
I started learning python myself as a hobby and I'm currently stuck with a csv tasks which I'm doing. See, I want to use the data from my excel csv as variables in my code, so I could use it in the body mass index calc.

One line in the csv consist of: Name, Height, Weight. For example: Mike, 190, 75

#the code goes as follows import csv with open('peoples_data.csv', 'r') as csv_file: reader = csv.reader(csv_file) for line in reader: print(line) #this is the formula I want to use the variables in: #BMI = ((1.3 * weight) / height**2.5) * 100000 
I want to find everyones BMI seperately (and possibly write a new file afterwards, but that I can do already). Any help is welcome cause I've been cracking my brains for 3 hours straight now searching for the way. Tongue
Reply
#2
Your code is already storing data from the csv in the variable line in your for loop. So when you print the line for the sample data you mentioned, it should look like ['Mike', ' 190', ' 75']. You could access the data directly in the line variable using indexes, or you could assign it to individual variables with a multi-assign statement like:
name, height, weight = line
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is it possible to extract 1 or 2 bits of data from MS project files? cubangt 8 6,236 Feb-16-2024, 12:02 AM
Last Post: deanhystad
  Create X Number of Variables and Assign Data RockBlok 8 6,567 Nov-14-2023, 08:46 AM
Last Post: perfringo
  script to calculate data in csv-files ledgreve 0 3,262 May-19-2023, 07:24 AM
Last Post: ledgreve
  SQL Alchemy help to extract sql data into csv files mg24 1 4,092 Sep-30-2022, 04:43 PM
Last Post: Larz60+
  Apply textual data cleaning to several CSV files ErcoleL99 0 1,780 Jul-09-2022, 03:01 PM
Last Post: ErcoleL99
  using variables with functions imported from different files. Scordomaniac 3 2,690 May-24-2022, 10:53 AM
Last Post: deanhystad
  Strategy on updating edits back to data table and object variables hammer 0 1,977 Dec-11-2021, 02:58 PM
Last Post: hammer
  Including data files in a package ChrisOfBristol 4 6,730 Oct-27-2021, 04:14 PM
Last Post: ChrisOfBristol
  Plotting sum of data files using simple code Laplace12 3 5,399 Jun-16-2021, 02:06 PM
Last Post: BashBedlam
  Passing Variables between files. victorTJ 3 3,759 Oct-17-2020, 01:45 AM
Last Post: snippsat

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.