python - 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)
解决方案
第一个问题:
readin = new.read
你没有调用方法,你不会得到文件内容readin
第二个问题:
if "docket =3ghi" == True:
您正在比较一个字符串是否为True
- 它从不True
。
推荐阅读
- compiler-errors - 无法使用 HDF5,因为它是由不同版本的 GNU Fortran 创建的
- oracle - Oracle SQL:从大型文本文件运行插入语句
- parsing - 用于 Web 抓取的 JSoup 或 XPath?
- go - 如何整合哨兵
- python - 如何在树莓派 4 型号 B 上使用 python 在蓝牙扬声器上播放音频
- java - 如何将风格融入主题?
- coq - 从另一个文件引用类型变量时出错
- javascript - 如何将常规功能变成承诺/异步等待?
- javascript - 如何在 div 中显示来自 websocket 的最近 10 次更新?
- reactjs - React Redux: update local state with a new value on action dispatch