Good night DEVs!
I'm having some difficulties in handling files in python. I have a TXT file with Float numbers.
Example:
numeros.txt
77 23 9 10 20.26 -20.26 2
Having this data in hand, I have to go through line by line, check if the file is empty or not, if it is empty I have to find the largest value within the file and the average of them, and this is where my doubt gains strength, how can I recover this data to perform the calculations? I have tried to save in a vet, however the data becomes strings and does not accept the conversion to Float.
I'll be leaving my code below:
#Ler o nome do arquivo
#Abrir o arquivo caso exista
#Verificar o Maior valor possivel
#Verificar a Média dos valores
#Imprimir média e Valores
def pulaLinha ():
print('\n')
arq = open("numeros.txt", "r") #ABRE O ARQUIVO TXT
########################################
#CALCULAR O TOTAL DE LINHAS DO ARQUIVO|#
########################################
text = arq.readlines()# GUARDA TODOS OS DADOS DO ARQUIVO
tot = 0 #TOTAL DE LINHAS
for i in text: #CALCULA O TOTAL DE LINHA DO ARQUIVO
tot = tot+1 #SALVA O TOTAL EM UM ACUMULADOR
########################################
#VERIFICAR SE O ARQUIVO É VAZIO OU NÃO #
########################################
if (tot == 0):#SE TOT DE LINHAS FOR IGUAL A 0
print("ARQUIVO VAZIO! ") #IMPRIME O ERRO
arq.close() # FECHA ARQUIVO
exit()
#SE O TOT DE LINHAS FOR MAIOR QUE 0
for linha in text:#ARMAZENA OS VALORES EM LINHA
print(linha, end=" ") #IMPRIME OS VALORES DE LINHA // IMPRIME O ARQUIVO
vet = []
for j in text:
vet.append(j)
arq.close()#FECHA O ARQUIVO TXT
If anyone can help me, I'll be grateful.
Thanks for your attention.