Read Data From CSV And Store In a Variable – Python
Updating the base code with multiple parameters is not a good idea specially when data keeps on changing. This can be simplified by passing the data from external file. Data can be stored in an external file and picked whenever required.
Below Python code picks the data from csv file and stores in a variable. The best way to pick the external data is, to keep the data in a csv file and pick it based on requirements.
There are many ways to read the data from csv file but the below is the simplest one.
Please follow the steps to read the data from csv file and store in a variable-
- Make sure you have installed python in your system.
- Open notepad, copy and paste the below code and save as .py file. For example- PythonCSV.py
import sys,argparse,csv with open ('testdata.csv') as csv_file: csv_reader=csv.DictReader(csv_file,delimiter=',') line_count=0 for row in csv_reader: Article1=row['Test1'] Article2=row['Test2'] print(Article1) print(Article2) csv_file.close()
In the above code, two values are picked from two different columns named Test1 and Test2.
Column Test1 contains value “Hello” and Test2 contains value “World”
Now let’s create a csv file with above column names and values.
3. Open a spread sheet and add below test data. Save the file as testdate.csv at location where python is installed. Data added in csv should be comma separated.
CSV file location Example-
CSV file data example-
Open the same file in notepad and make sure all the data are comma separated.
4. Open command prompt and type python folder location.
cd C:\Users\Testingfreak\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6>
5.Type below code once entered in python folder.
C:\Users\Testingfreak\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6> C:\Users\Testingfreak\Desktop\PythonCSV.py
6.Type below code once entered in python folder.
C:\Users\Testingfreak\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.6> C:\Users\Testingfreak\Desktop\PythonCSV.py
Here external csv data are stored in Article1 and Article2 variables.
Now the values are stored successfully in the variables. This is the simplest way to pick the data from csv, however you can read and store all the csv data in a dictionary object or in an array.
Leave a Reply