How to correlate 2 different txt in python?

Asked

Viewed 189 times

0

Input data:

Primeiro txt
77777777777777777777
Id x y
1 6655.5 -3132.0
2 1122.3 -1234.0
3 4455.6 -5678.9

Segundo txt
Id e n z 
1 111 222 333
2 444 555 666
3 777 888 999

Resultado qual eu preciso: 
7777777777777
1 6655.5 -3132.0 111 222 333
2 1122.3 -1234.0 444 555 666
3 4455.6 -5678.9 777 888 999

What I have done so far only joins 2 files, but only files with same number of lines, follows the code:

with open('text1.txt', 'r') as f1, open('text2.txt', 'r') as f2:
    f1_text = f1.read().splitlines()
    f2_text = f2.read().splitlines()
with open('text3.txt', 'w+') as f3:
    for i, item in enumerate(f1_text):
        value1 = f1_text[i].split(None, 1)[1].rstrip('\n')
        value2 = f2_text[i].split(None, 1)[1].rstrip('\n')
        if i == 0:
            i = 'Id'
        f3.write(str(i) + ' ' + value1 + ' ' + value2 + '\n')

with open('text3.txt', 'r') as f3:
    print(f3.read())

I have tried to make some modifications, but nothing I need. If anyone can help me in this problem I would appreciate.

1 answer

1

I understand that you need to join two (or more) txt files.

I thought of this way:

First read the arquivo_1 and save in a lista_1.

Then read the arquivo_2 and save in a lista_2.

Lastly merge_lista receives the two lists and saved on arquivo_novo

arquivo_1, arquivo_2 = "arquivo_1.txt", "arquivo_2.txt"

def ler_arquivo(arquivo):

        lista=[]

        arq = open(arquivo, "r")

        for linha in arq :

                lista.append(linha)

        arq.close()

        return lista


lista_1 = ler_arquivo(arquivo_1)

lista_1.append("\n")

lista_2 = ler_arquivo(arquivo_2)


merge_lista = lista_1.copy()

merge_lista.extend(lista_2)


arq = open("arquivo_novo.txt", 'w')

arq.writelines(merge_lista)

arq.close()

Exit:

Texto do arquivo um.
Texto do arquivo um.
Texto do arquivo um.
Texto do arquivo dois.
Texto do arquivo dois.
Texto do arquivo dois.
  • yes, I need to join two files, but it needs to be like in the example of the row merge result and deleting the column descriptions. Thank you for your help friend, I will try to work with the idea of lists now

  • You can use the linha.strip("\n") if you don’t want to break the page. Another tip would be linha.replace("nome_coluna","") to disappear with the name of the columns. If you need help I am at your disposal. If my answer helped you, please mark as right. Good luck!

Browser other questions tagged

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