我的文本文件包含如下列表。
** sample.txt文本文件内容**:
[[" Sanjay"," Bangalore"," 100"],[" Akshay"," Pune&#34 ;," 101"],[" Pranay","德里"," 102"]]
要求:
我必须迭代上面列表中的每个列表,并将列表中的每个项目分配给变量。
测试用例
${FILECONTENT}= Get File sample.txt
Log to console ${FILECONTENT}
: FOR ${ELEMENT} IN ${FILECONTENT}
\ ${NAME}= ${ELEMENT}[0]
\ ${CITY}= ${ELEMENT}[1]
\ ${ID}= ${ELEMENT}[2]
\ Log to console ${ELEMENT}
Log to console For loop is over
我无法循环内容,因为它没有将内容视为列表列表。
任何人都可以帮助实现这一目标。
答案 0 :(得分:3)
您提供的示例代码存在一些问题。首先,最重要的是您需要将字符串转换为list-in-list构造。然后你需要正确地迭代它,最后以正确的方式分配变量。
由于没有本地关键字允许即时字符串列表转换,我为它创建了一个自定义关键字库,并将其作为List.py
存储在与机器人脚本相同的文件夹中:< / p>
import ast
class List(object):
ROBOT_LIBRARY_VERSION = 1.0
def __init__(self):
pass
def ConvertToListFromString(self, ListString):
x = ast.literal_eval(ListString)
return x
然后可以使用该库在机器人中创建功能:
*** Settings ***
Library OperatingSystem
Library List
*** Test Cases ***
Sample
${FILECONTENT}= Get File sample.txt
@{list} Convert To List From String ${FILECONTENT}
Log to Console ${EMPTY}
: FOR ${ELEMENT} IN @{list}
\ ${NAME} Set Variable ${ELEMENT[0]}
\ ${CITY} Set Variable ${ELEMENT[1]}
\ ${ID} Set Variable ${ELEMENT[2]}
\
\ Log to console Name=${NAME}, City=${CITY}, Id=${ID}
然后导致:
Command: C:\Python27\python.exe -m robot.run -P C:\Eclipse\Workspace\ExternalList
-s ExternalList.ExternalList C:\Eclipse\Workspace\ExternalList
Suite Executor: Robot Framework 3.0 (Python 2.7.9 on win32)
==============================================================================
ExternalList
==============================================================================
ExternalList.ExternalList
==============================================================================
Sample
Name=Sanjay, City=Bangalore, Id=100
Name=Akshay, City=Pune, Id=101
Name=Pranay, City=Delhi, Id=102
| PASS |
------------------------------------------------------------------------------
ExternalList.ExternalList | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
ExternalList | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Output: C:\Eclipse\Workspace\ExternalList\output.xml
Log: C:\Eclipse\Workspace\ExternalList\log.html
Report: C:\Eclipse\Workspace\ExternalList\report.html
应该注意的是,读取文件并将其转换为代码会带来一些需要减轻的安全风险。因此,上述代码并非生产就绪。
答案 1 :(得分:1)
如果数据是有效的JSON,您可以将数据转换为JSON,然后非常容易地迭代值:
${FILECONTENT}= Get File sample.txt
${JSON}= evaluate json.loads($FILECONTENT) json
:FOR ${ELEMENT} IN @{JSON}
\ ${NAME} Set Variable ${ELEMENT[0]}
\ ${CITY} Set Variable ${ELEMENT[1]}
\ ${ID} Set Variable ${ELEMENT[2]}
\ Log to console element: ${ELEMENT}
注意:FOR循环中的其他语句不正确。要设置新变量,您必须调用Set Variable关键字。这就是我在示例代码中更改它们的原因。