Adding text files to python

Asked

Viewed 2,681 times

3

I have a series of files in . txt and I would like to add them / join them all in one using a python script.

something like:

#Abre o arquivo que receberá a soma de todos os outros
arq.open("redação.txt", "w")

#escreve todas as linhas de cada arquivo por vez (Aqui está meu problema!)
arq.write(arq=(texto1.txt + texto2.txt + texto3.txt + texto4.txt + texto5.txt))

#Fecha o arquivo
arq.close

I’ve researched the sum of files and texts in python, but I haven’t found anything specifically this way

  • 1

    Easier to make from the command line. Linux:cat aqr1 arq2 arq3 > destino .Windows:type aqr1 arq2 arq3 > destino .

3 answers

4

I do not know if I understood your question right, you want to open some files and join all in 1 only?

If so, try the following:

arq = open("resultado.txt", "w") 
arq1 = open("texto1.txt", "r")
arq2 = open("texto2.txt", "r")
arq.write(arq1.read()+arq2.read())
arq.close()

If that’s not what you wanted, try to explain the doubt more.

  • 2

    Gabriel, it worked. .

  • yes, I’m glad you were able to solve the problem

4


When you open a file, a generator referring to the file is returned. You can pass it directly to the method writelines to write your content in the final file. See the example:

# Abre o arquivo redacao.txt para escrita:
with open("redacao.txt", "w") as file:

    # Percorre a lista de arquivos a serem lidos:
    for temp in ["texto1.txt", "texto2.txt", "texto3.txt"]:

        # Abre cada arquivo para leitura:
        with open(temp, "r") as t:

            # Escreve no arquivo o conteúdo:
            file.writelines(t)

Considering the archives:

texto1.txt

a1
a2
a3

texto2.txt

b1
b2
b3

texto3.txt

c1
c2
c3

The archive redacao.txt will be:

a1
a2
a3
b1
b2
b3
c1
c2
c3
  • Tested and approved.

1

I don’t like to ask for file names interactively, or for them to become fixed; I prefer to create scripts that receive parameters via the command line. In this sense I recommend the fileinput module. Be cat.py

#!/usr/bin/python3

import fileinput
for linha in fileinput.input():
   print(linha.strip())

This way the script works as a normal Unix command, and on the command line we can give zero (stdin, Pipes) or more files to process.

We can now use cat.py with any number of files.

$ cat.py  texto*.txt > redação.txt

Browser other questions tagged

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