Hello, there is the following task:
There are 2 txt files (the number of lines in each is arbitrary). It is necessary to insert lines from one list into another at a certain interval, for example, after every n lines.
f1 = open(r'c:\Исходная база.txt') f2 = open(r'c:\Строки для добавления.txt') list1 = f1.readlines() list2 = f2.readlines() f1.close() f2.close() i = 0 n = 2 while i + n <= 10: list1.insert(i * n, list2[i]) i = i + 1 with open(r'c:\результат.txt', 'w') as res: for item in list1: res.write("{}".format(item)) In case you specify
while i + n <= len(list2): list2 - file from where we take the string for substitution, the code works as it should.
However, with
while i + n <= len(list1): I get the error:
list1.insert(i * n, list2[i]) IndexError: list index out of range I ask you to suggest how to implement the substitution of rows from list2 in the case if there are fewer rows in list2 than in list1. That is, when the lines in list2 run out, string substitution should start again from 0 on list2 again.
Исходные данные list1: 1, 2, 3, 4, .., m Исходные данные List2: a, b, c, d, .., k Результат должен быть: 1, a, 2, b, 3, c ... при n=2 1, 2, a, 3, 4, b, .. при n=3 At the same time it is important that the lines are substituted from list2 to list1. And when the lines in list2 run out, they should begin to be substituted again with 0 elements.