问题
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.
回答1:
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}
回答2:
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)
回答3:
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
来源:https://stackoverflow.com/questions/21858822/how-to-read-the-csv-file-in-robot-framework-for-data-verification