描述:
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(' ')) for newline in f2.readlines(): print(newline.strip(' ')) with open('E:/b.txt', 'a') as i: i.write("""HOSTNAME:{IP} NAME:{HOST} IP:{IP} """.format(IP=line.strip(' '),HOST=newline.strip(' ')))
问题: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(' '), HOST=next(f2).strip(' '))) 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(' '),HOST=next(f22).strip(' '))) except StopIteration: pass