我有两个文件
文件1:
IdName1 Info1 Info2 Info3 #Info: from program1 for name1 #Info: from program2 for name1
IdName2 Info1 Info2 Info3 #Info: from program1 for name2 #Info: from program2 for name2
IdName4 Info1 Info2 Info3 #Info: from program1 for name4
IdName3 Info1 Info2 Info3 #Info: from program1 for name3 #Info: from program2 for name3
文件2:
# ProgramInfo
# Query: IdName1 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
line1
line2
# ProgramInfo
# Query: IdName2 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
# ProgramInfo
# Query: IdName4 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
line1
line2
line3
line4
现在我需要检查“#Query:”之后的“IdName1 Info1 Info2 Info3”是否在 File2 中,如果是,我需要从 File1 中的该行拆分信息并将其插入 File2 中相应的“# ProgramInfo”行之前. 输出文件应如下所示:
输出文件:
# IdName1 Info1 Info2 Info3
# Info: from program1 for name1
# Info: from program2 for name1
# ProgramInfo
# Query: IdName1 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
line1
line2
# IdName2 Info1 Info2 Info3
# Info: from program1 for name2
# Info: from program2 for name2
# ProgramInfo
# Query: IdName2 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
# IdName4 Info1 Info2 Info3
# Info: from program1 for name4
# ProgramInfo
# Query: IdName4 Info1 Info2 Info3
# DatabaseInfo
# FiledInfo
line1
line2
line3
line4
我现在的问题是,如何将相应的三行添加到 File2 中,我一直在尝试这样的事情:
import sys
def programs_info_comb(fileName1, fileName2):
my_file1 = open(fileName1, "r")
my_line1=my_file1.readlines()
my_file2 = open(fileName2, "r")
my_line2=my_file2.readlines()
for line1 in my_line1:
(name1, info1, info2)= line1.strip().split("\t")
for line2 in my_line2:
if line2.startswith("# Q"):
name2 = line2[9:-1]
if name1 == name2:
#### here Im lost how to tell where I want those next two lines to be printed
print "#"+" "+name1
print info1
print info2
my_file1.close
my_file2.close
if __name__== "__main__":
programs_info_comb(sys.argv[1], sys.argv[2])
可能有更好更简单的方法,所有帮助将不胜感激谢谢您的时间 Daeja