Python:最后添加的行而不是文件中的Replace

问题描述 投票:0回答:2

我是python的新手,实际上我正在编写Python脚本来替换文件中的特定行,但是最后添加的行代替文件中的Replace。

下面是我的代码的快照请看 -

假设file1和file2不同,

d = file2.readline()
z = file1.readline()

if d in z:
    print("Match_Found")
    file2.write(z.replace(d, ""))

上面的代码不会替换该行的特定字符串,

任何人都可以帮助我谢谢

python python-3.x str-replace
2个回答
0
投票

您可以尝试从文件中读取,然后写入另一个(新)文件。

逐行读取输入文件。如果该行不匹配,只需将其按原样写入输出文件即可。如果它“匹配”,则在输出文件中写入替换字符串。

如果您确实要替换文件(不创建新文件),可以删除输入文件并重命名输出文件。


0
投票

这是一个示例:

import io

with open('sample1.txt', 'r') as f:
   lines1 = list(f)


with open('sample2.txt', 'r') as f1:
   lines2 = list(f1)

count = len(lines1)
counter = 0

for k in range(0, count):
   if lines2[counter] == lines1[counter]:
      with open('sample2.txt', 'a') as f3:
          print("Match found!")
          f3.write('\n' + lines1[counter])

 counter += 1

您想要在追加模式下打开要写入的文件,并且要使用新行字符以开始新行。 'a'用于追加模式。

© www.soinside.com 2019 - 2024. All rights reserved.