Automate reading of multiple text files in a Python script

1

I have a Python script that counts the number of connections contained in a text file and is working perfectly:

with open('1zao.txt') as f:
    linhas = f.readlines()

soma = 0
for linha in linhas:
    soma += int(linha.strip().split(" ")[0])

print("O total por segundo eh",soma)

Where 1zao.txt looks like this:

  1 10:19:00 192.168.91.115
  1 10:19:00 192.168.91.119
  1 10:19:00 192.168.91.122
  1 10:19:00 192.168.91.133
  3 10:19:00 192.168.91.137
  1 10:19:00 192.168.91.149
  1 10:19:00 192.168.91.180
  1 10:19:00 192.168.91.49
  1 10:19:00 192.168.91.73
  1 10:19:00 192.168.91.76
  1 10:19:00 192.168.91.90
  1 10:19:00 192.168.91.96
  1 10:19:01 192.168.91.108
  1 10:19:01 192.168.91.119
  1 10:19:01 192.168.91.124

Number | schedule | IP

The input files are all of the form 1zao.txt,2zao.txt... 80zao.txt

I would like to modify the above Python script so that I do not have to be swapping the name of the text file every time I run it.

Gostaria que a saída fosse num arquivo, por exemplo resultado.txt:

  1->  O total por segundo no arquivo 1zao.txt é: soma

  2->  O total por segundo no arquivo 2zao.txt é: soma

Is it possible?

    
asked by anonymous 10.07.2017 / 15:28

1 answer

2

You can use what was explained in this question: List files from one folder in Python

#encoding: utf-8
import os    

#lista apenas os arquivos txt da pasta
pasta = "c:\scripts"
caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)]    
arquivos_txt = [arq for arq in arquivos if arq.lower().endswith(".txt")]

#cria uma lista para armazenar as saídas
saida = []    

#percorre os arquivos
for arq in arquivos_txt:    
  #abre o arquivo 
  with open(arq) as f:
      linhas = f.readlines()

  #soma os valores
  soma = 0
  for linha in linhas:
     soma += int(linha.strip().split(" ")[0])

  #guarda na lista de saida  
  saida.append("O total por segundo no arquivo {} é: {} \n".format(arquivos_txt,soma))

#grava a lista em um novo arquivo
arq_saida = open('/arquivo_saida.txt', 'w')
arq_saida.writelines(saida)
arq_saida.close()
    
10.07.2017 / 15:42