如何拆分单行显示的stings

时间:2017-06-22 03:26:26

标签: split robotframework

curl命令的响应将数据作为单行返回(如下所示)。我想将下面的列名称拆分为放置值的行。

目前它将输出显示为

import foo "."

我想以下面的格式保存输出(psv格式)

[ {
  "file" : "XXXX",
  "key" : "XYZ123456789",
  "previousSource" : "2017-05-23",
  "previousValue" : -1,
  "currentSource" : "2017-05-24",
  "currentValue" : -1
 }]

请告诉我转换为此格式的方法。

1 个答案:

答案 0 :(得分:0)

最好的方法是使用python内置的csv库。 制作一个Helper.py文件并在那里添加此代码。

import csv
def write_in_csv(filename, data, source='dict', write_mode='a'):
    len = get_csv_length(filename)
    with open(filename, write_mode) as csvfile:
        if source == 'list':
            writer = csv.writer(csvfile)
        else:
            writer = csv.DictWriter(csvfile, fieldnames=data.keys())
        if len == 0 and source == 'dict':
            writer.writeheader()
        writer.writerow(data)

现在在您的机器人文件中:

假设$ {response}有你的卷曲响应:

${response}=  Remove String  ${response}  {  [  }  ]  ${SPACE}  "
${response_list}  Split String  ${response}  :
${response_list_length}  Get Length  ${response_list}
${count}  Set Variable  ${0}
${response_dict}  Create Dictionary
:FOR  ${index}  IN RANGE  ${response_list_length}/2
\  Set to dictionary  ${response_dict}  ${response_list[${count}]}=${response_list[${count+1}]}
\  ${count}  Evaluate  ${count} + 2
write in csv  ${csv_file_path}  ${response_dict}