Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

you can try this: I haven’t tested it yet though

lst = []
with open("id","r") as f:
    ids = f.read().split('\n')
    file_name = 'text.txt'
    with open(file_name,'r') as fnr:
        text = fnr.read().split('\n')
        counter = 0
        for id_num in ids:
            for _ in range(5):
                if counter >= len(text):
                    break
                lst.append(id_num + " " + text[counter])
                counter += 1

text = '\n'.join(lst)
with open(file_name,'w') as fnw:
    fnw.write(text)

output:

1 pla pla pla
1 text text text
1 dsfdfdfdfd
1 klfdklfkdkf
1 poepwoepwo
2 lewepwlew
2 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading