[英]Finding and Replacing string in a line
I am trying to open a file and search for a particular string in a line and replace it with another string.我正在尝试打开一个文件并搜索一行中的特定字符串并将其替换为另一个字符串。
I am trying the following code.我正在尝试以下代码。
def myFunct(file, test, patter, replace):
with open(file, mode='r') as f:
for line in f.readline():
if str(line).__contains__(test):
if patter in line:
print("Found here\n")
print(line)
f.close()
The code does not seem to go into the for loop.代码似乎没有进入 for 循环。 Any suggestions ?
有什么建议 ?
I have also tried a similar solution with the same problem.我也尝试过类似的解决方案来解决同样的问题。
You are only reading the first line and iterate over the single characters of that line.您只阅读第一行并遍历该行的单个字符。 You have to remove the
readline
:您必须删除
readline
:
def myFunct(file, test, patter, replace):
with open(file, mode='r') as f:
for line in f:
if test in line and patter in line:
print("Found here\n")
print(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.