【问题标题】:Check if a line exists in one file, to all other lines in another file检查一个文件中是否存在一行,以及另一个文件中的所有其他行
【发布时间】:2019-08-23 16:53:24
【问题描述】:

我有三个文件,两个正在打开以供阅读,最后一个正在写入。我想遍历一个读取文件中的每一行并检查该行是否存在于另一个读取文件中。然后将相同的行输出到写入文件,如果不存在则为空白。我无法弄清楚如何将一行与所有行进行比较并为每一行进行比较。

我在示例文本文件中尝试了以下代码:

import os

file_path = os.getcwd()

output_file = os.path.join(file_path, "output_file.txt")
read_file1 = os.path.join(file_path, "read_file1.txt")
read_file2 = os.path.join(file_path, "read_file2.txt")

with open(output_file, 'w+') as write:
    write.write("")

with open(read_file1, 'r') as read1:
    with open(read_file2, 'r') as read2:
        with open(output_file, 'a+') as write1:
            for line in read1:
                if line in read2:
                   write1.write(line)
                else:
                   write1.write("blank\n")

read_file1 的内容:

test1
test2
test4
test6
test8
test9
test44
test109

read_file2 的内容:

test1
test2
test3
test4
test5
test6
test8
test9
test11
test44
test45
test99
test109
test276

output_file 中的预期输出为:

test1    
test2
blank
test4
blank
test6
test8
test9
blank
test44
blank
blank
test109
blank

我得到的输出是:

test1
test2
test4
test6
test8
test9
test44
blank

【问题讨论】:

    标签: python python-3.x loops


    【解决方案1】:

    您必须在 for 循环中反转 read1read2。 (demo)

    # ...
    
    with open(read_file1, 'r') as read1:
      f1 = read1.read().split()
    
    with open(read_file2, 'r') as read2:
      f2 = read2.read().split()
    
    with open(output_file, 'w+') as write1:
      for line in f2:
        if line in f1:
          write1.write(line + '\n')
        else:
          write1.write('blank\n')
    

    【讨论】:

      【解决方案2】:

      希望对你有帮助

      import os
      
      file_path = os.getcwd()
      
      output_file = os.path.join(file_path, "output_file.txt")
      read_file1 = os.path.join(file_path, "read_file1.txt")
      read_file2 = os.path.join(file_path, "read_file2.txt")
      
      read_list = []
      with open(read_file1,'r') as read1:
          for i in read1:
              read_list.append(i)
          j = len(read_list)
          read_list[j-1] = read_list[j-1] + "\n"
      print(read_list)
      
      write_list = []
      with open(read_file2,'r') as read2:
          for line in read2:
              if(line in read_list):
                  write_list.append(line)
              else:
                  write_list.append("blank\n")
      with open(output_file, 'w+') as write1:
          for i in write_list:
              write1.write(i) 
      

      【讨论】:

        猜你喜欢
        • 2014-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-03
        • 2014-12-26
        • 2012-08-26
        • 2011-02-12
        • 2015-10-11
        相关资源
        最近更新 更多