Adding text files with python

0

I have a series of files in .txt and would like to sum them all together using a script in python.

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 have already researched the sum of files and texts in python, but I did not find anything specifically this way

    
asked by anonymous 26.05.2017 / 03:33

3 answers

2

When you open a file, a generator is returned for the file. You can pass it directly to the writelines method to write its contents to 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 files:

texto1.txt

a1
a2
a3

texto2.txt

b1
b2
b3

texto3.txt

c1
c2
c3

The file redacao.txt will be:

a1
a2
a3
b1
b2
b3
c1
c2
c3
    
26.05.2017 / 04:03
2

I do not know if I understand your question right, you want to open several files and put them together in 1 so?

If this is the case, 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 this is not what you wanted, try to make it clearer.

    
26.05.2017 / 04:00
0

I do not like to ask file names interactively, or to keep them fixed; I prefer creating 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())

In this way the script works like a normal Unix command, and in 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
    
26.05.2017 / 16:16