Home > Back-end >  How can i add string at the beginning each line?
How can i add string at the beginning each line?

Time:05-20

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 

CodePudding user response:

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 

CodePudding user response:

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.

  • Related