How to join texts in a file?

0

I'm trying to develop a program, which does the following:

From 1 to 100, it writes the word "test" in a text file.

And after that, I want it to match the word "test" WITH EACH LINE with its lines from another text file.

I ran the program, and it wrote 100 lines with the word "test", however, I do not know how to join with each line of the other file.

HowdoImergewitheachlineofthisothertextfile?

Asaresultthis(Ididnotmakeupto100,becauseitisverylaborious):

Mysourcecode:

arquivo=open('arquivo_teste.txt','w')outro_arquivo=open('letrasaleatórias.txt','w')foriinrange(0,100):""" 
        Preciso escrever em cada linha "teste" + o conteúdo de cada linha do outro arquivo. 

        No caso, "outro_arquivo", ali de cima.
    """
    arquivo.writelines('teste')

    # Usei para dar espaço(um embaixo do outro) e não ficar deste jeito: 
    # testetestetestetestetestetestetestetestetestetesteteste 
    arquivo.write('\n')

arquivo.close()
outro_arquivo.close()
    
asked by anonymous 13.01.2018 / 16:49

2 answers

2

To write to the files (this part you already have):

from random import sample
from string import ascii_lowercase

print('\n'.join('teste' for _ in range(100)), file=open('1.txt', 'w'))
print('\n'.join(''.join(sample(ascii_lowercase, 10)) for _ in range(100)), file=open('2.txt', 'w')) # escrever no ficheiro letras aleatorias

There are several ways to do it:

1.

This might be the one I'd use

together = ''
with open('1.txt') as f1, open('2.txt') as f2:
    for linha_teste, linha_letras in zip(f1, f2):
        together += '{}{}'.format(linha_teste.strip(), linha_letras)

2.

together = ''
with open('1.txt') as f1, open('2.txt') as f2:
    for l in f1:
        together += '{}{}'.format(l.strip(), f2.readline())

3.

with open('1.txt') as f1, open('2.txt') as f2:
    together = ''.join('{}{}'.format(f1.readline().strip(), f2.readline()) for _ in f1)

4.

together = ''
with open('1.txt') as f1, open('2.txt') as f2:
    linhas1 = f1.readlines() # obter uma lista com cada linha
    linhas2 = f2.readlines() # obter uma lista com cada linha
    for idx, l1 in enumerate(linhas1):
        together += '{}{}'.format(l1.strip(), linhas2[idx])

Then to see the content you can:

print(together)
    
13.01.2018 / 17:22
0
One way to do this is: Open another blank file and go through the lines in sequence of each file and concatenate line 1 of file 1 with line 1 of file 2 and give add > in file 3 and so on with the other lines.

    
13.01.2018 / 17:07