3 回答

TA贡献1752条经验 获得超4个赞
让我们分解一下您当前的陈述:
if "docket = 3ghi" == True:
非空字符串的计算结果类似于True,但不完全是 True。True是一个布尔值,所以你问“这个字符串是一个布尔值吗?” 那总是False:
"somestr" == True
# False
修复它以检查字符串是否是in文件的一部分。例如:
with open(("test.txt",'r') as new:
for line in new.read(): # read in the file and iterate
if "somestr" in line:
# do something
注意我还添加了括号,new.read()这样你就不会得到像function doesn't support iteration

TA贡献1794条经验 获得超8个赞
第一个问题:
readin = new.read
您没有调用该方法,您将无法获取文件内容 readin
第二个问题:
if "docket =3ghi" == True:
您正在比较字符串是否为True
- 它从不True
。

TA贡献1828条经验 获得超6个赞
您需要正确调用该方法才能将文件的全部内容放在readin. 现在你可以replace两次检查也正确的条件
with open('test.txt', 'r') as new:
readin = new.read()
if 'docket="3ghi"' in readin:
readin = readin.replace('"I"', '"new"').replace('"II"', '"fair"')
# save or print or do whatever you want with readin
添加回答
举报