【问题标题】:How to replace text / string in a file with robotframework如何用机器人框架替换文件中的文本/字符串
【发布时间】:2021-10-28 20:20:46
【问题描述】:

我在当前工作目录中复制了一个文件。该文件有一段文字:

订单价值=78

我想用新的替换这个文本

包裹价值= 500

我该怎么做?

【问题讨论】:

    标签: robotframework


    【解决方案1】:

    使用操作系统库中的Get File,您可以读取文件的内容,
    并使用字符串库中的Replace String,您可以替换字符串和 使用操作系统库中的Create File,您可以创建该文件。

    【讨论】:

      【解决方案2】:

      如果您要替换的文件很大并且您不想将整个文件内容加载到变量中,那么您可以使用操作系统库中的Run 关键字。该关键字将执行shell命令,这里是“sed”并进行替换。 (当然,在这种情况下你应该在 Linux 上)

      例如:

      *** Settings ***
      | Library | OperatingSystem
      
      *** Test Cases ***
      | Example of replacing the text in a file
      | | ${result}= | Run | sed -i 's/foo/bar/g' myfile.txt
      

      变量result 将保存运行shell 命令后得到的标准输出。

      【讨论】:

        【解决方案3】:

        我正在为此使用 python 脚本。将下面的代码放入 .py 文件中,并使用设置部分中的库将其加载到您的机器人文件中。 接下来在机器人文件中使用这个关键字:

        替换文件中的行 |文件 |搜索Exp1 |替换线

        def Replace_line_in_file(file,searchExp1,replaceLine):
            """ Open a file (like input.txt) and find the line that
                contains the string searchExp1.
                and replace that complete line by replaceLine.
                When there are multiple lines that contain searchExp1
                then all those lines will be replaced
            """
            for line in fileinput.input(file, inplace=1):
                if searchExp1 in line:
                    line = replaceLine+'\n'
                sys.stdout.write(line)
        

        【讨论】:

          【解决方案4】:

          我尝试使用上述关键字“替换文件中的行”。 但我收到错误:Exception TypeError: TypeError("'NoneType' object is not callable",) in > ignored

          还需要进行哪些其他更改。

          【讨论】:

          • 这将更适合作为评论 - 不是答案,因为它不回答问题。
          猜你喜欢
          • 2020-11-30
          • 2023-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多