I want to read a CSV file for data verification. Any library or Keywords for reading CSV file would do. I am using Robot Framework with Ride.
3 Answers
You can easily create your own library in python for reading and writing csv files. Doing so lets you create any keywords you want. You could simply read and return all the data, or have a keyword that returns the number of rows, or the number of columns, or anything else.
Example keyword to read a csv file:
Save the following definition in a file named csvLibrary.py. It creates a keyword library with a single keyword named "read csv file". Pass is the path to a csv file and it will return the data as a list of lists.
import csv
class csvLibrary(object):
def read_csv_file(self, filename):
'''This creates a keyword named "Read CSV File"
This keyword takes one argument, which is a path to a .csv file. It
returns a list of rows, with each row being a list of the data in
each column.
'''
data = []
with open(filename, 'rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
data.append(row)
return data
Example test:
This test will use the csvLibrary to open up a .csv file, read it, and return the result as a list of lists:
*** Settings ***
| Library | csvLibrary.py
*** Test cases ***
| Reading a csv file
| | ${data}= | read csv file | test.csv
| | log | ${data}
7 Comments
read csv file is the keyword we created in the library (def read_csv_file). As I wrote in the answer, it returns a list of lists. So, ${data[0]} will have the first row of data, ${data[0][0]} is the first column of the first row, etc. If you run the code and then look at the log, you'll see exactly what is in ${data}.${data}= goes in one cell, read csv file goes in another, test.csv goes in another.I did similar thing as follows:
${content} | Get File | ${dir}/Newfolder2/random.xml
Should Contain | ${content} | ${text}
where: ${content}, ${dir} and ${text} are just some variables (names should be rather self-explanatory) and Get File and Should Contain are standard keywords (for Get File you have to import OperatingSystem lib)
Comments
i would fix the for loop that you wrote in your py script first. i ran into the exact same issue where i would have to call a subset of subset in my list index (ie data[0][0] instead of data[0]). I wrote my for loop like this:
data = []
with open(filename, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter='<something here>')
for row in reader:
for i in row:
data.append(i)
return data
if your csv file comes from excel, you can use the argument:
reader = csv.reader(csvfile, delimiter=',', dialect='excel')
as well