# Extract data from csv in RASA

**URL:** https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775
**Category:** Rasa Open Source
**Created:** [March 2, 2021, 10:22am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775 "2021-03-02T10:22:36Z")
**Posts on this page:** 17
**Page:** 1

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 2, 2021, 10:22am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/1 "2021-03-02T10:22:36Z")

</div>

I am making a chatbot in RASA which helps High school graduates find university according to their desired location. I have all my data stored in a CSV file. So is there any way we can extract some specific data from that CSV. Example: If a user asks to show universities available in a certain location, how to extract the specific data from CSV which is the name of the university according to the location given by the user.

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [March 2, 2021, 11:27am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/2 "2021-03-02T11:27:37Z")

</div>

You can use [custom actions](https://rasa.com/docs/action-server/sdk-actions).

In your custom action, you can connect to a database or read a CSV file like in [any other Python code](https://docs.python.org/3/library/csv.html).

If you use [slots](https://rasa.com/docs/rasa/next/domain#slots), you can get the value of the slot in the custom action by using `tracker.get_slot(slot_name)`.

You do your stuff with the CSV as with any other Python code and get the output, build a reply based on the output, and use the `dispatcher.utter_message(reply)` function to make the chatbot utter the message.

For example, in the `run()` method of your custom action:

```auto
# get the location slot
location = tracker.get_slot('location')

# read the CSV file
with open('universities.csv', 'r') as file:
    reader = csv.DictReader(file)
    # get a list of universities in the desired location
    output = [row for row in reader if row['Location'] == location]

if output: # there is at least one value
    # build your reply according to the output
    reply = f"This is a list of universities in {location}:"
    reply += "\n- " + "\n- ".join([item['Name'] for item in output])
    # utter the message
    dispatcher.utter_message(reply)

else: # the list is empty
    dispatcher.utter_message(f"I could not find universities in {location}")

```

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 2, 2021, 1:05pm UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/3 "2021-03-02T13:05:05Z")

</div>

thank you. helped me a lot

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 4, 2021, 6:03am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/4 "2021-03-04T06:03:23Z")

</div>

@ChrisRahme i did this and i am getting errors.Can you please recheck this?

class actionfindengr(Action):

```
def name(self) -> Text:

 return "action_findengr"

 def run(self, dispatcher: CollectingDispatcher,

         tracker: Tracker,

         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

    # get the location slot

     location = tracker.get_slot('location')

     # read the CSV file

     with open('data\Engineering colllege.csv', 'r') as file:

        reader = csv.DictReader(file)

        # get a list of universities in the desired location

        output = [row for row in reader if row['Location'] == location]

     if output: 

        reply = f"This is a list of universities in {location}:"

        reply += "\n- " + "\n- ".join([item['Name'] for item in output])

        # utter the message

        dispatcher.utter_message(reply)

     else: # the list is empty

        dispatcher.utter_message(f"I could not find universities in {location}")
```

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [March 4, 2021, 6:05am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/5 "2021-03-04T06:05:02Z")

</div>

What’s the error?

For a start:

- You should use `\\` or `/` in the path instead of `\`.
- Is your file named `data/Engineering colllege.csv` or `data/Engineering college.csv`?
- Are your column names `Name` and `Location`?

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 4, 2021, 6:35am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/6 "2021-03-04T06:35:26Z")

</div>

rasa.shared.exceptions.RasaException: Failed to execute custom action.

raise NotImplementedError(“An action must implement its run method”) NotImplementedError: An action must implement its run method so these are the errors i am getting i changed my action to: from typing import Any, Text, Dict, List

from rasa\_sdk import Action, Tracker

from rasa\_sdk.executor import CollectingDispatcher

import csv

class actionfindengr(Action):

```
def name(self) -> Text:

 return "action_findengr"

 def run(self, dispatcher: CollectingDispatcher,

         tracker: Tracker,

         domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

    # get the location slot

     location = tracker.get_slot('location')

     # read the CSV file

     with open('data/Engineering colllege.csv', 'r') as file:

        reader = csv.DictReader(file)

        # get a list of universities in the desired location

        output = [row for row in reader if row['Location'] == location]

     if output: 

        reply = f"This is a list of universities in {location}:"

        reply += "\n- " + "\n- ".join([item['College'] for item in output])

        # utter the message

        dispatcher.utter_message(reply)

     else: # the list is empty

        dispatcher.utter_message(f"I could not find universities in {location}")

```

still the same error .and i have defined my action in domain and stories as well

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [March 4, 2021, 6:47am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/7 "2021-03-04T06:47:52Z")

</div>

Can you send me your `actions.py`?

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 4, 2021, 6:48am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/8 "2021-03-04T06:48:59Z")

</div>

[actions.py](https://forum.rasa.com/uploads/short-url/uUjEza6OFZ6FUb4TPd3mso2HoLP.py) (1.8 KB)@ChrisRahme here you go

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [March 4, 2021, 6:55am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/9 "2021-03-04T06:55:42Z")

</div>

As I expected, it’s an error of indentation. Be careful with your indents in Python. [actions.py](https://forum.rasa.com/uploads/short-url/dv5IN7ER14BoWC5wfYxQPm8rBXi.py) (1.8 KB)

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 5, 2021, 8:38am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/10 "2021-03-05T08:38:25Z")

</div>

@ChrisRahme can you check on this please i am quite new to this and i am not getting solutions .

> **[AayushDangol123/rasa](https://github.com/AayushDangol123/rasa)**
>
> Contribute to AayushDangol123/rasa development by creating an account on GitHub.

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [March 5, 2021, 11:27am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/11 "2021-03-05T11:27:51Z")

</div>

Your problem is that in your code you wrote `row['location']` while the CSV key is `Location` with a big L.

I also added `.lower()` in the following line

```auto
output = [row for row in reader if row['Location'].lower() == location.lower()]

```

so that “trade tower” and “Trade Tower” match.

Conversation before adding `.lower()`:

```auto
Your input -> hi
? Hey! How can i help you?? 1: find a college.. (/affirm)
ok..what field do you want to study in??
Your input -> engineering
can you specify the location where you want to be studying??
Your input -> trade tower
I could not find universities in trade tower
Your input -> Trade Tower
This is a list of universities in Trade Tower:
- The British College, Kathmandu

```

[chatbot.zip](https://forum.rasa.com/uploads/short-url/dFkdElncUvpjvraL97g0UT7sq2t.zip) (7.2 KB)

---

<div class="post-metadata">

### Author: ![AayushDangol123](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/aayushdangol123/32/13470_2.png) [@AayushDangol123](https://forum.rasa.com/u/AayushDangol123)
#### Post date: [March 7, 2021, 5:11am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/12 "2021-03-07T05:11:04Z")

</div>

Thankyou so much

---

<div class="post-metadata">

### Author: ![Akshat\_Vashisht](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Akshat\_Vashisht](https://forum.rasa.com/u/Akshat_Vashisht)
#### Post date: [November 16, 2021, 1:59am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/13 "2021-11-16T01:59:21Z")

</div>

Hello sir @ChrisRahmeI am making a chatbot in RASA which will help customer to find several details . Like if users asks What is the revenue for Company A? then chatbot should reply “for which year”.

(example) User: 2020 Chatbot: shows the revenue for Company A

and should return the value what ever is asked by the user. [CSV\_FILE.csv](https://forum.rasa.com/uploads/short-url/g416sZJhqCoGcWysWDVXvvhwHXl.csv) (993 Bytes) is my .csv file from which My seniors wants that chat bot should extract the information from .csv file and should retern it to use, Same as the condition defined above by AayushDangol123 . My no. of columns are more so could you please help me in building that code because I am new to this.

I shall be highly thankful to you.

---

<div class="post-metadata">

### Author: ![Akshat\_Vashisht](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Akshat\_Vashisht](https://forum.rasa.com/u/Akshat_Vashisht)
#### Post date: [November 16, 2021, 2:58am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/14 "2021-11-16T02:58:33Z")

</div>

code I have written in action.py file

from typing import Any, Text, Dict, List

from rasa\_sdk import Action, Tracker

from rasa\_sdk.executor import CollectingDispatcher

import csv

class actionfindengr(Action):

```
def name(self) -> Text:

    return "action_findengr"

def run(self,

        dispatcher: CollectingDispatcher,

        tracker: Tracker,

        domain: Dict[Text, Any]

    ) -> List[Dict[Text, Any]]:

    # get the location slot

    location = tracker.get_slot('location')

    # read the CSV file

    with open('C:\\Users\\om sai infotech\\OneDrive\\Desktop\\bot\\actions\\financial.csv','r',encoding = "utf-8") as file:

        reader = csv.DictReader(file)

        # get a list of universities in the desired location

        output = [row for row in reader if row['Location'] == location]

    if output:

        reply = f"Output: {location}:"

        reply += "\n- " + "\n- ".join([item['S.No.','date','firm','Ticker','Research Development','Income Before Tax','Net Income','Selling General Administrative','Gross Profit','Ebit','Operating Income','Interest Expense','Income Tax Expense','Total Revenue','Total Operating Expenses','Cost Of Revenue','Total Other Income Expense Net','Net Income From Continuing Ops','Net Income Applicable To Common Shares'] for item in output])

        # utter the message

        dispatcher.utter_message(reply)

    else: # the list is empty

        dispatcher.utter_message(f"I could not this in {location}")
```

---

<div class="post-metadata">

### Author: ![Akshat\_Vashisht](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Akshat\_Vashisht](https://forum.rasa.com/u/Akshat_Vashisht)
#### Post date: [November 16, 2021, 3:22am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/15 "2021-11-16T03:22:19Z")

</div>

> [@Akshat\_Vashisht](#):
>
> from typing import Any, Text, Dict, List
> 
> from rasa\_sdk import Action, Tracker
> 
> from rasa\_sdk.executor import CollectingDispatcher
> 
> import csv
> 
> class actionfindengr(Action):
> 
> ```auto
> def name(self) -> Text:
> 
> return "action_findengr"
> 
> def run(self,
> 
> dispatcher: CollectingDispatcher,
> 
> tracker: Tracker,
> 
> domain: Dict[Text, Any]
> 
> ) -> List[Dict[Text, Any]]:
> 
> # get the location slot
> 
> location = tracker.get_slot('location')
> 
> # read the CSV file
> 
> with open('C:\\Users\\om sai infotech\\OneDrive\\Desktop\\bot\\actions\\financial.csv','r',encoding = "utf-8") as file:
> 
> reader = csv.DictReader(file)
> 
> # get a list of universities in the desired location
> 
> output = [row for row in reader if row['Location'] == location]
> 
> if output:
> 
> reply = f"Output: {location}:"
> 
> reply += "\n- " + "\n- ".join([item['S.No.','date','firm','Ticker','Research Development','Income Before Tax','Net Income','Selling General Administrative','Gross Profit','Ebit','Operating Income','Interest Expense','Income Tax Expense','Total Revenue','Total Operating Expenses','Cost Of Revenue','Total Other Income Expense Net','Net Income From Continuing Ops','Net Income Applicable To Common Shares'] for item in output])
> 
> # utter the message
> 
> dispatcher.utter_message(reply)
> 
> else: # the list is empty
> 
> dispatcher.utter_message(f"I could not this in {location}")
> 
> ```

Could you please tell that whether the above code is right or wrong? if wrong then how can I do it correct?

---

<div class="post-metadata">

### Author: ![Akshat\_Vashisht](https://avatars.discourse-cdn.com/v4/letter/a/ecccb3/32.png) [@Akshat\_Vashisht](https://forum.rasa.com/u/Akshat_Vashisht)
#### Post date: [November 16, 2021, 3:24am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/16 "2021-11-16T03:24:10Z")

</div>

When I run the command “rasa init” It removes the above shared code from the file. Could you please help @ChrisRahme

---

<div class="post-metadata">

### Author: ![ChrisRahme](https://dub1.discourse-cdn.com/flex013/user_avatar/forum.rasa.com/chrisrahme/32/15572_2.png) [@ChrisRahme](https://forum.rasa.com/u/ChrisRahme)
#### Post date: [November 16, 2021, 6:20am UTC](https://forum.rasa.com/t/extract-data-from-csv-in-rasa/40775/17 "2021-11-16T06:20:16Z")

</div>

`rasa init` restarts your project, you should only do it once.

For the rest, it’s just Python, I suggest asking this question on [https://stackoverflow.com/](https://stackoverflow.com/).
