【问题标题】:Python: line appending at the end instead of Replace in a filePython:在文件末尾追加行而不是替换
【发布时间】:2018-09-05 12:20:16
【问题描述】:

我是 python 新手, 实际上,我正在编写 Python 脚本来替换文件中的特定行,但在末尾追加行而不是文件中的替换。

下面是我的代码截图,请看-

假设file1和file2不同,

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

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

以上代码不会替换该行的具体字符串,

谁能帮帮我谢谢

【问题讨论】:

  • 如果文件 d 中的一行在文件 z 中可用,那么您想让该行为空吗?
  • 是的,没错
  • 同样的问题。但就我而言,我想替换同一个文件。有什么解决方法吗?

标签: python python-3.x str-replace


【解决方案1】:

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

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

如果你真的想替换文件(不是创建一个新文件),你可以删除你的输入文件并重命名你的输出文件。

【讨论】:

    【解决方案2】:

    这是一个示例:

    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' 表示附加模式。

    【讨论】:

    • 如果 file1 和 file2 不同?那么这个解决方案将无法正常工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2015-08-12
    • 1970-01-01
    • 2014-06-02
    • 2016-10-25
    相关资源
    最近更新 更多