Automate reading multiple text files in a Python script

Asked

Viewed 845 times

0

I have a Python script that counts the number of connections contained in a text file and that 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 is 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| time| IP

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

I would like to modify the above Python script so as not to keep changing the name of the text file each 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

It is possible?

1 answer

2


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

#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()
  • Beautiful code. I’ll test it. Thank you very much!

  • output is possible in a file, for example result.txt: 1-> The total per second in the file 1zao.txt is: sum 2-> The total per second in the file 2zao.txt is: sum

  • I ran the script with the updated file path but did nothing! Here’s the code: https://pastebin.com/Q9Rxs35F

  • I changed it to record in a file and put it to him to print how many files he listed, can run and tell me if it returns any file

  • Thank you for your attention. I will now test and return!

  • ran but gave "0 listed files" and the empty output file!

  • There was a problem in the following section, caminhos = [os.path.join(pasta, nome) for nome in os.listdir(pasta)]
arquivos = [arq for arq in caminhos if os.path.isfile(arq)], made the correction

  • I’ll be back! Thank you

  • The error has now been: Traceback (Most recent call last): File "/Radhe/Lababril2017captures/slices_calculations/10Abril/timeSlices_1min/slowloris/Slices_1min/contar_Otimizado2.py", line 16, in <module> lines = f.readlines() File "/usr/lib/python3.5/codecs.py", line 321, in Decode (result, Consumed) = self. _buffer_decode(data, self.errors, final) Unicodedecodeerror: 'utf-8' codec can’t Decode byte 0xd4 in position 0: invalid continuation byte

  • The error was http://imgur.com/a/LCncf

  • The error seems to be happening because of a file’s Unicode, are you using that example you passed? or are there more files? If yes you can see in which file it triggered the error?

  • In the folder there are PCAP files too. It has how to tell the script to see only the files in the way xzao.txt?

  • Edited to return only . txt files

  • Nameerror: name 'Arq' is not defined

Show 10 more comments

Browser other questions tagged

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