我想将file1的第一列内容与file2的元素相匹配,然后输出文件1的四列内容:
如何更改我的代码(如下所示)以从输入文件中获取所需的输出:
我的代码:
infile1=open("file1.txt","r")
infile2=open("file2","r")
outfile=open("out.txt","w")
for file2 in infile2:
file2=file2.rstrip()
print file2
for file1 in infile1:
file1=file1.rstrip().split("\t")
print file1[3]
if file1[3].strip()==file2.rstrip():
if file2.rstrip() in file1[3]:
print file1
#outfile.write("\t".join(file1[0],file1[1],file1[2]] + "\n"))
outfile.write("\n".join(file1.rstrip() for file1 in infile1))
infile1:
col1 col2 col3 col4
1 20 H-H UU_290
1 15 GB XX_245
3 16 GB UM_790
3 16 G-B2 UM_791
4 16 MM UX_234
infile2:
XX_245
UM_790
OUTFILE:
col1 col2 col3 col4
1 15 GB XX_245
3 16 GB UM_790
谢谢
答案 0 :(得分:0)
infile1=open("file1.txt","r")
infile2=open("file2","r")
import re
outfile=open("out.txt","w")
for file1 in infile1:
print file1
for file2 in infile2:
print file2
if re.findall(r"(?<=[ ])"+file2+"\n$",file1):
outfile.write(file1)
您只需使用re
执行此操作。