首页 > 解决方案 > replace string if a condition is satisfied in python

问题描述

I have a file that looks like this, if docket ="3ghi" (i could be "3ghi" or 5"ghi" )in the file then condition is greater than 4 should be changed to "new" and condition <=2 should be changed to "fair" . I added my code below, the replace command works but my if loop is bad. Please help.

Input:
<code=report docket="3ghi" parse=20>
    <items="20" product="abc" condition="9">
    <items="50" product="xyz" condition="8">
    <items="" product="mno" condition="2">

Output:
<code=report docket="3ghi" parse=20>
    <items="20" product="abc" condition="new">
    <items="50" product="xyz" condition="new">
    <items="" product="mno" condition="fair">

with open(("test.txt",'r') as new:
   readin = new.read
   if "docket =3ghi" == True:
        readin.replace('condition="4-100"', 'condition="new"')
        readin.replace('condition="1-2"', 'condition="fair"')
        x.write(readin)

标签: python

解决方案


第一个问题:

readin = new.read

你没有调用方法,你不会得到文件内容readin

第二个问题:

if "docket =3ghi" == True:

您正在比较一个字符串是否为True- 它从不True


推荐阅读