How to read a csv file - Part 1 - single column

Problem

You want to read a csv file into an array. The csv file contains only single column such as below:

URL
google.com
youtue.com
facebook.com
twitter.com
amazon.com

Solution

We read the entire csv file, split them into lines, then read the value of each line.

The underlying language of TagUI is javascript. As such, you can use many of the javascript functions right inside TagUI script.

Sample Code

array_items = []
csv_file = 'one_column_data.csv'
load '+csv_file+' to lines

array_lines = lines.split('\n')

for (n=0; n<array_lines.length; n++) 
{
  array_items[n] = array_lines[n].trim()
}

The content of the csv file is now contained in the array array_items.

Explanation

Line 1: Create an empty array
Line 2: Specify the filename
Line 3: Read the entire csv into the string variable lines using the load command.
Line 5: Split the string variable lines into an array of individual lines using the javascript function split()
Line 7:
  • Loop through each line using for loop
  • You can find out the number of lines in the csv file using array_lines.length
  • Line 9:
  • Store each line into the array array_items
  • Strip away any whitespace from both ends of a string using the javascript function trim(). Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.)
  • Output

    You can display the content of the array array_items using the following code:

    for (n=0; n<array_lines.length; n++) 
    {
      echo n+". item = " + array_items[n]
    }
    

    The output is as follows:

    0. item = URL
    1. item = google.com
    2. item = youtue.com
    3. item = facebook.com
    4. item = twitter.com
    5. item = amazon.com
    

    Note that javascript array starts from 0. The first item (array item 0) is the column heading.

    Variations

    If you just want to process the data, you may want to start from 1 as follows:

    for (n=1; n<array_lines.length; n++) 
    {
      echo n+". item = " + array_items[n]
    }
    

    The output will then be as follows:

    1. item = google.com
    2. item = youtue.com
    3. item = facebook.com
    4. item = twitter.com
    5. item = amazon.com
    

    Related Articles

    Other Resources

    TagUI Tutorials

    Questions / Comments

    If you have any questions or comments on the codes above, you can leave your comments below, or post your questions in the RPA Community Forum.

    Comments (0)

    There are no comments posted here yet

    Leave your comments

    Posting comment as a guest. Sign up or login to your account.
    Attachments (0 / 3)
    Share Your Location