Python逐行合并两个文件内容
描述:
1.txt内容(IP地址)
192.168.1.212 192.168.1.213 192.168.1.214 192.168.1.215
2.txt内容(主机描述)
测试数据库-DB01 测试数据库-DB02 测试-APP01
测试-APP02
1、第一版(错误)
with open('E:/1.txt') as f1,open('E:/2.txt',encoding='UTF-8') as f2: for line in f1.readlines(): print(line.strip('\n')) for newline in f2.readlines(): print(newline.strip('\n')) with open('E:/b.txt', 'a') as i: i.write("""HOSTNAME:{IP} NAME:{HOST} IP:{IP} """.format(IP=line.strip('\n'),HOST=newline.strip('\n')))
问题:IP相同,都为1.txt中的最后一个IP。
2、第二版(正确)
def read_file(filename): with open(filename, encoding='utf-8') as file_obj: for line in file_obj: yield line.strip() def write_fiel(filename,mode='a'): with open(filename,mode,encoding='utf-8') as file_obj: f1 = read_file('E:/1.txt') f2 = read_file('E:/2.txt') try: while True: file_obj.write("""HOSTNAME:{IP} NAME:{HOST} IP:{IP} """.format(IP=next(f1).strip('\n'), HOST=next(f2).strip('\n'))) except StopIteration: pass if __name__ == '__main__': write_fiel('E:/3.txt')
3、第三版(和第二版没什么区别)
def read_file (filename): with open(filename, encoding='utf-8') as file_obj: for line in file_obj: yield line.strip() with open('E:/b.txt', 'a') as i: f11 = read_file('E:/1.txt') f22= read_file('E:/2.txt') try: while True: i.write("""HOSTNAME:{IP} NAME:{HOST} IP:{IP} """.format(IP=next(f11).strip('\n'),HOST=next(f22).strip('\n'))) except StopIteration: pass
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步