'How can i add string at the beginning each line?

I need to add at beginning of each line id from a list five times. file_id like

5
8
6
9

text_file like

pla pla pla 
text text text 
dsfdfdfdfd
klfdklfkdkf
poepwoepwo
lewepwlew

the result should be

5 pla pla pla 
5  text text text
5  dsfdfdfdfd
5  klfdklfkdkf
5  poepwoepwo
8  lewepwlew

and so on .. the number of ids equals 5000 ids and text equals 25000 sentences .. every id will be with five sentences. i tried to do something like that

import fileinput
import sys   
f = open("id","r")
List=[]
for id in f.readlines():
    List.append(id)    
file_name = 'text.txt'    
with open(file_name,'r') as fnr:
    text = fnr.readlines()
i=0
text = "".join([List[i]+" " + line.rstrip()  for line in text])    
with open(file_name,'w') as fnw:
    fnw.write(text)

but got results

 5
 pla pla pla5
 text text text5
 dsfdfdfdfd5
 klfdklfkdkf5
 poepwoepwo5
 lewepwlew5 


Solution 1:[1]

Instead of:

i=0
text = "".join([List[i]+" " + line.rstrip()  for line in text])

You can try:

new_text = []
for i, line in enumerate(text):
    new_text.append(List[i % 5] + " " + line.rstrip())

And then write new_text to the file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aryerez