未能打印第二个文件中未匹配的行
出于某种原因,我没有得到Python的迭代。我有两个文件,文件1和文件-2。我必须使用文件-1行在文件-2中查找行。File-1 lines:
03/28/2021,P,6,LINE2
03/28/2021,P,9,LINE4
File-2 lines:
03/28/2021,P,16,LINE1
03/28/2021,P,6,LINE2
03/28/2021,P,9,LINE3
03/28/2021,P,9,LINE4
03/28/2021,P,8,LINE5
03/28/2021,S,95,LINE6
03/28/2021,S,1,LINE7
03/28/2021,P,46,LINE8
I need to print out only lines that do not match:
03/28/2021,P,16,LINE1
03/28/2021,P,9,LINE3
03/28/2021,P,8,LINE5
03/28/2021,S,95,LINE6
03/28/2021,S,1,LINE7
03/28/2021,P,46,LINE8
But the code I wrote prints this:
ELSE -->> 03/28/2021,P,16,LINE1
ELSE -->> 03/28/2021,P,9,LINE3
ELSE -->> 03/28/2021
, P,9,LINE4 ELSE -- >> 03/28/2021,P,8,LINE5
ELSE -- >> 03/28/2021,S,95,LINE6
ELSE - >>03/28/2021,S,1,LINE7
ELSE -- >> 03/28/2021,P,46,LINE8
ELSE -- >>03/28/2021,P,16,LINE1
ELSE - >>03/28/2021,P,6,LINE2
ELSE -- >> 03/28/2021,P,9,LINE3
ELSE -- >> 03/28/2021,P,8,LINE5
ELSE - >>03/28/2021,S,95
,LINE6 ELSE - >> 03/28/2021,S,1,LINE7
ELSE - >>03/28/2021,P,46,LINE8
我必须在文件-1和文件-2中拆分线,在行中需要一些额外的处理。
以下是代码:
with open (file_2,'r') as l_few :
f2=l_few.readlines()
with open (file_1,'r') as f1:
for lf1 in f1:
lf1=lf1.strip()
sp1 = lf1.split(",")
for lf2 in f2 :
lf2=lf2.strip()
if lf2 :
if sp1 in lf2 :
spL2=lf2.split(",")
#print (" File 2 Line matched --> "+lf2)
#break
else :
print (" ELSE -->> "+lf2)
#break
首先,"l_few"(行数较少的文件)根据文本进行file_1,因此我交换了文件名称,以便在原始程序中尽可能少地更改。
然后,我想出这个,希望它有助于,请注意,我没有太大的变化,只是足以让它打印你需要的:with open ('file_2','r') as l_few :
f2=l_few.readlines()
sp23 = .strip() for s in f2] # collect all the terms you need to compare
with open ('file_1','r') as f1:
for lf1 in f1:
lf1=lf1.strip()
sp1 = lf1.split(",")
if sp1 in sp23:
pass # here we have a match so print nothing
# spL2=lf2.split(",")
#print (" File 2 Line matched --> "+lf2)
#break
else :
print (lf1) # print the non-matching line
#break 我无法直接比较文件。我需要处理行后,在这两个文件中的行将不分。 仍然可以使用一套。它将比比较字符串更有效。首先构建您正在寻找的一组字符串,然后在第二个文件中读取并检查与设置。with open(DIR/'lines_to_look_for.txt', 'r') as file:
lines = set( for line in file])
with open(DIR/'check_for_lines.txt', 'r') as file:
for line in file:
line = line.strip()
if line.split(',') in lines:
print(f'{line} MATCH')
else:
print(f'{line} NO MATCH')
页:
[1]