How to join texts in a file?

Asked

Viewed 457 times

0

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

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

And after that, I want him to join the word "test" OF EACH LINE with the respective lines of 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.

inserir a descrição da imagem aqui

How do I join with each line of this other text file?

inserir a descrição da imagem aqui

As a result of that(I did not make up to 100, because it is very laborious): inserir a descrição da imagem aqui

My source code:

arquivo = open('arquivo_teste.txt', 'w')
outro_arquivo = open('letras aleatórias.txt', 'w')

for i in range(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()
  • Do you already have both files filled with the 100 lines? Just need to know how to join both the right contents?

  • That’s right, buddy!!

2 answers

2


To write to 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

Otherwise, there are several ways to do:

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 contents you can:

print(together)
  • Miguel, I saw that you changed the solutions.

  • I’m getting better and bigger @Brkappa

  • I made a two types of script to do what I wanted (edited according to your first solution before). I’ll leave it on Pastebin, because I don’t know how to format it in the comment! https://pastebin.com/ATvpJHnT https://pastebin.com/jbUcY3PP

  • Anyone should give

  • According to what I edited, you think it got better, what? I mean, good practice, and clean code? I’m a beginner, so I didn’t really understand some codes, so sorry for the mistakes. But, you managed to get what I wanted!! :)

  • Ah, and when I open the file with "With", I have to close it with close() or don’t need?

  • I put in the reply @Brkappa, the number 2 maybe

  • No @Brkappa required, when you exit indentation the file is closed, you do not need the close()

  • 1

    Oops, thank you! Helped me solve all my questions!!

  • You’re welcome @Brkappa, thank goodness

  • @Brkappa by the way, I would use the 1 and not the 2, but they are the same, just for the sake of reading

Show 6 more comments

0

One way to do it is: Open another blank file and read the lines in sequence of each file and concatenate line 1 of file 1 with line 1 of file 2 and give one add in file 3 and so on with the other lines.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.