我有2个这样的文件。
档案1
e 1 0 ppp
e 3 1 rrr
e 3 2 rrr
文件2
e 1 0 rrr
我想分割每行代码来比较数组[3]如果行相同的rrr,它应该打印OK
。我写这样的代码。
file1 = open('file1.txt', 'r', encoding="utf8")
file2 = open('file2.txt', 'r')
for line1 in file1: #loop file1
L1 = line1.split() #split to array
if(L1[0] == 'e'):
print("line1 " + line1)
for line2 in file2: #loop file2
L2 = line2.split() #split to array
if(L2[0] == 'e'):
print("line2 " + line2)
if(L2[3] == L1[3]): #check rrr same
print("OK")
当我运行代码时,它打印出来:
line1 e 1 0 ppp
line2 e 1 0 rrr
line1 e 3 1 rrr
line1 e 3 2 rrr
代码是循环循环我想显示如下结果:
line1 e 1 0 ppp
line2 e 1 0 rrr
line1 e 3 1 rrr
line2 e 1 0 rrr
line1 e 3 2 rrr
line2 e 1 0 rrr
如何修改代码以比较文件的每一行?
答案 0 :(得分:0)
基本上你需要跟踪两个文件的最后一行。如果任何文件较小,则在另一个文件之前完成迭代。 您需要将当前行与另一个文件中的上一行进行比较。
怎么样?
prev_f1_token = None
prev_f1_line = None
prev_f2_token = None
prev_f2_line = None
with open('file1.txt') as f1:
with open('file2.txt') as f2:
for line in f1:
prev_f1_token = line[0]
prev_f1_line = line
for line in f2:
prev_f2_token = line[0]
prev_f2_line = line
if(prev_f1_token == 'e'):
print("line1 ", prev_f1_line)
if (prev_f2_token == 'e'):
print ("line2 ", prev_f2_line)
if(prev_f2_line.split()[3] == prev_f1_line.split()[3]): #check rrr same
print("OK")
答案 1 :(得分:0)
你编写的代码多于它所需要的代码,如果你的代码得到了很多缩进,那么继续编写代码并不总是一个好主意。这是我试图打印你想要的东西,我相信这可以缩短更多!
您可以在此处使用itertools.cycle
(如果列表较短,则返回循环迭代器)
import itertools
f1, f2 = open('file1.txt', 'r'), open('file2.txt', 'r')
file1, file2 = f1.read().split(), f2.read().split()
if len(file1) > len(file2):
file2 = itertools.cycle(file2)
else:
file1 = itertools.cycle(file1)
print '\n'.join(['line1 '+i+'\nline2 '+j for i,j in zip(file1, file2)])
f1.close();f2.close()