How to take a specific data type from a text file

Asked

Viewed 1,007 times

0

I have a text file, structured as follows

  • 1
  • Name
  • CPF
  • Address
  • Telephone

would like to know how I do to pick up only the lines that contain integer, in case the code(identified as 1), because I am trying to make an auto increment in python Note: there is something I should do to improve this formatting, I appreciate the comments

Note: Code of writing

codigo = verifica_codigo_cliente()
nome = raw_input("Digite o nome do Cliente: ")
cpf = raw_input("Digite o CPF do Cliente: ")
endereco = raw_input("Digite o endereço do Cliente: ")
telefone = raw_input("Digite o telefone do Cliente: ")
arquivo_cliente.write(codigo)
arquivo_cliente.write("\n" + nome + "\n")
arquivo_cliente.write(cpf + "\n")
arquivo_cliente.write(endereco + "\n")
arquivo_cliente.write(telefone + "\n\n")

Function to verify the code, that’s where I got lost

def verifica_codigo_cliente():
arquivo_cliente = open("arquivo_cliente.txt", "a+")
codigos = []
for row in arquivo_cliente:
    codigos.append(row)
if codigos == []:
    return 1
else:
    x = codigos[len]
    return codigos[x]
  • You already know how to open and read a Python file?

  • Yes, I can open the file and even read his data. the problem is that I didn’t quite understand the difference between read, readline and readlines, even after reading the documentation

  • You can put that code in the question?

  • I already put it in question

  • Before answering, you have already considered some better format for storing the data, such as CSV?

  • the file must be in txt, but if I structure it with comma after each data, it will still work?

Show 1 more comment

1 answer

1


Correcting the function verifica_codigo_cliente()

# Identação errada
def verifica_codigo_cliente():
# "a+" = read e append.A função só faz leitura,substitua por 'r'
arquivo_cliente = open("arquivo_cliente.txt", "a+")
codigos = []
#Podemos ler apenas a última linha ao invés de iterar todo o arquivo
for row in arquivo_cliente:
    codigos.append(row)
if codigos == []:
    return 1
else:
    #uso correto: x = len(codigos)
    x = codigos[len]
    return codigos[x]

Rewriting function:

def verifica_codigo_cliente(arquivo):
    try:
        arquivo_clientes = open(arquivo, 'r')
        ultima_linha = arquivo_clientes.readlines()[-1]
        #separa primeira coluna da ultima linha(separador=",")
        id = ultima_linha.split(",")[0]
        return id
    except:
        return 1
    finally:
        arquivo_clientes.close()

Rewritten program

there is something I should do to improve this formatting, I appreciate the comments

I rewrote your code using the module csv(that the Anderson mentioned). The format is the same that you wanted to use,:

  • each data is separated by a comma
  • one customer on each line
  • starts with an "id", which increases as more customers are added

file should be in txt, but if I structure it with comma after each data, it will still work?

CSV is pure text, just save in .txt instead of .csv.Any questions just ask!

NOTE: written for python3

#!/usr/bin/python3
import csv
import os

arquivo = "clientes.txt"

def arquivo_existe():
    return os.path.isfile(arquivo)

def proximo_id():
    with open(arquivo, 'r') as arquivo_clientes:
        reader = csv.reader(arquivo_clientes)
        ultima_linha = list(reader)[-1]
        id = ultima_linha[0]
        return (int(id)+1)

def escreve_dados(id, nome, cpf, endereco, telefone):
    with open(arquivo, 'a') as arquivo_clientes:
        writer = csv.writer(arquivo_clientes)
        writer.writerow([id, nome, cpf, endereco, telefone])

nome = input("Digite o nome do cliente: ")
cpf = input("Digite o CPF do cliente:   ")
endereco = input("Digite o endereco do cliente: ")
telefone = input("Digite o Telefone do cliente: ")
if(arquivo_existe()):
    escreve_dados(str(proximo_id()), nome, cpf, endereco, telefone)
else:
    escreve_dados(1, nome ,cpf, endereco, telefone)
  • Thank you so much for the tips, it helped a lot

  • You are welcome, João! Thank you if you can accept my answer as the correct one

Browser other questions tagged

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