2015-09-23 51 views
-2

我试图打开一个文件,然后搜索在一条线上一个特定的字符串并用另一个字符串替换它更换字符串。查找和线

我正在尝试以下代码。

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循环。 有什么建议吗?

我也尝试了一个类似的解决方案,同样的问题。

Find and Replace

+0

你的意思是'for line in f.readlines()'?注意's'。 –

+0

'test'和'patter'有什么区别? – ozgur

+0

@ozgur测试是我搜索和图案是我想在含测试 – Ram

回答

0

你只阅读第一行,遍历该行的单个字符。你必须删除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) 
+0

我已经试过你提到的更新,但我我有同样的问题。代码似乎没有进入for循环。 – Ram