2017-08-09 123 views
-2

我有一个在其中列出了一定字符串的文档两次。 我只想更改第一行或仅更改第二行。我如何指定?如何仅替换文档行中第一次或第二次出现的字符串?

我已经看过例子,我看到人们做这样的事情:

line.replace('8055', '8006') 

更改为:

line.replace('8055', '8006', 1) # 1 means only change the first occurence of this string 8005 in a line 

这里是我的代码:

try: 
     source = '//' + servername + r'/c$/my dir/mydocument.config' 
     with open(source,'r') as f: # you must first read file and save lines 
      newlines = [] 
      for line in f.readlines(): 
       newlines.append(line.replace('8055', '8006', 1)) # 1 means only change the first occurence of this string 8005 in a line 
     with open(source, 'w') as f: # then you can open and write 
      for line in newlines: 
       f.seek(
       f.write(line) 
     f.close() 
    except: 
     pass 

这是为什么不工作? 这改变了两条线,而不是仅仅1

UPDATE

try: 
     line_changed = False 
     source = '//' + servername + r'/c$/my dir/myfile.config' 
     with open(source,'r') as f: # you must first read file and save lines 
      newlines = [] 
      for line in f.readlines(): 
       if not line_changed: 
        old_line = line 
        line = line.replace('8055', '8006', 1) # 1 means only change the first occurence of this string 8005 in a line 
        if not old_line == line: 
         line_changed = True 
       newlines.append(line) 
     with open(source, 'w') as f: # then you can open and write 
      for line in newlines: 
       f.write(line) 
     f.close() 
    except: 
     pass 
+1

你会得到什么错误?它以什么方式不起作用? – thaavik

+0

它使每行更换1个。所以每次在新行上调用'line.replace()'时,它都会执行一次替换。 –

回答

1
line_changed = False 
with open(source,'r') as f: # you must first read file and save lines 
    newlines = [] 
    for line in f.readlines(): 
     if not line_changed: 
      old_line = line 
      line = line.replace('8055', '8006', 1) 
      if not old_line == line: 
       line_changed = True 
     newlines.append(line) 

这将使程序在第一次发生更改后不再查找要更改的行。

+0

这是删除我改变第一行后的所有行。 – Prox

+0

@Prox我更新了代码,现在它将在更改一行后继续读取。 –

+0

我在顶部添加了我正在尝试的内容。 UPDATE部分下的代码是否正确?这不会改变我的任何事情。 – Prox

0

此代码工作:)

比方说,你有这样的文件:

myfile.txt的

8055 hello 8055 8055 
8055 
hello 8055 world 8055 
hi there 

A压脚提升运行程序,它具有以下内容:

8006 hello 8055 8055 
8006 
hello 8006 world 8055 
hi there 

也就是说,你的代码只在每行更换项目1。这就是line.replace(...)中发生的情况。

如果您只希望它替换整个文档中的一个,那么您应该针对整个文件内容的字符串调用replace()方法!

还有其他方法可以做到这一点 - 例如,您可以为每一行调用replace(),并且一旦有一行有替换,当迭代文件的其余部分时停止调用该方法。由你决定什么是有道理的。

相关问题