How to append data to csv file in Robot Framework?

我与影子孤独终老i 提交于 2019-12-23 22:57:58

问题


I would like to append data to .csv file which is not empty in Robot Framework now, but I meet some questions.

I installed CSVLibrary from 's4int' of 'robotframework-CSVLibrary' in github and it has a keyword named 'Append To Csv File'. I can append data into .csv file but there are some issues with the format.

First I have an empty csv file and I run my scripts in Robot Framework.

*** Settings ***
Library           Selenium2Library
Library           CSVLibrary

*** Variables ***

*** Test Cases ***
test
${list}=    Create List    apple    pear
Append To Csv File    ${file_path}    ${list}   

The file is looked like this:

But I expect is:

!

How can I append data to show like what I expect? Is my format wrong? Or is there any other way to realize it? Thanks a lot.


回答1:


It appears that with the library you are using, Append to csv file requires a list of lists. Each list represents a row, and each sublist represents the columns in the row.

Since you want "apple" and "pear" to be on the same row, you need to put those in a list, and then put that list in another list.

*** Test Cases ***
test
    ${list}=    Create List    apple    pear
    ${data}=    create list    ${list}
    Append To Csv File    ${file_path}    ${data}  



回答2:


If you need to clear the file first and then write another data to it, then you can use below keyword for your robot framework script.

You can directly use the code and create a library with the name CSVLibrary.py and start using it. Then you can call it to your script. Provide the file path with \\ slash to work in the robot framework. eg: E:\\FOLDER1\\FOLDER2. You can give the data in the same way your were giving ${list}=Create List apple pear.

import csv

class CSVLibrary():   

def Clear_file(self, filepath):                    #  Clear_file :it will clear your file. 
 with open(filepath, 'w+') as f:
     obj1=csv.writer(f)

def Append_file(self, filepath, data):             #  Append_file :it will append the data you wanted to in your script. 
  with open(filepath, 'a') as f:
      obj1=csv.writer(f)
      obj1.writerow(data) 


来源:https://stackoverflow.com/questions/45137586/how-to-append-data-to-csv-file-in-robot-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!