[英]Finding and Replacing string in a line
我正在嘗試打開一個文件並搜索一行中的特定字符串並將其替換為另一個字符串。
我正在嘗試以下代碼。
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()
代碼似乎沒有進入 for 循環。 有什么建議 ?
我也嘗試過類似的解決方案來解決同樣的問題。
您只閱讀第一行並遍歷該行的單個字符。 您必須刪除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.