Problems with python code in file i / o

3

Hello, I am new to python, I'm programming in 3.5.1, I was doing a piece of code that reads and then draws a line from a file:

lista = {}  
# Essa função lê o arquivo e divide ele em linhas, em palavras e depois coloca dentro de um dicionario
# e a primeira palavra de uma linha é a chave das outras palavras da linha
def upd():  
    file = open("bd.glc","rt")  
    text = list(map(lambda l: l.split(" "),file.readlines()))  
    file.close()  
    p = 0  
    while p < len(text):  
        text[p][-1] = text[p][-1].replace("\n","")  
        p += 1  
    p = 0  
    while p < len(text):  
        lista.update({text[p][0]:text[p][1:-1]})  
        p += 1  
upd()  
# Pergunta qual cliente deve ser deletado
resd = input("\nQual o id do cliente\n>>>")  
if resd in lista:  
    file = open("bd.glc","wt")
    # Aqui é dificil de explicar mas basicamente escreve no arquivo todas as linhas menos a linhas
    # com a chave que vai ser deletada  
    for k,v in lista.items():  
        if k == resd:  
            continue  
        else:  
            file.write(k)  
            for i in v:  
                file.write(" " + i)  
            file.write("\n")

link

And he is deleting the entire file rather than delete the file and put all the lines less to be cleared. (The program should do it because I do not know how to delete a text directly in the file)

    
asked by anonymous 09.07.2016 / 14:10

1 answer

2

I made a slightly simpler version with some good python practices.

file_name = 'test.txt'


def read_file():
    with open(file_name, 'r') as reader:
        content = [line.split() for line in reader.readlines()]
    # se a primeira palavra da linha se repetir será sobrescrita
    return {line[0]: ' '.join(line) for line in content}


def write_file(file_content):
    with open(file_name, 'w') as writer:
        for line in file_content.values():
            writer.write('{}\n'.format(line))


if __name__ == '__main__':
    file_content = read_file()
    key_to_remove = input('Qual o id do cliente\n>> ')
    if key_to_remove in file_content:
        file_content.pop(key_to_remove)
        write_file(file_content)

Basically this script has:

  • A function to read the file and return its contents in a dictionary (the key being the first word of the line that was read, as you were intending to do)

  • A function to write to the text file the contents of the dictionary (values only)

  • At the end where it is checked whether this script is what python is running , I read the file, I ask the user for the "id" of the line he wants to remove and if that "id" is in the dictionary (which contains the contents of the file), I remove that dictionary record and rewrite the file.

Some "languages" that might be new to you:

  • with : We use with here to involve the use of the file that was opened using the open function in a context . With this, you do not have to worry about closing the file and running the risk of leaving it open (which may have been your problem), the context manger takes care of it, when leaving the context the file will be closed

  • list comprehensions and dict comprehensions: basically I simplified a couple of for using list comp ( [x for x in some_iterable] ) and dict comp ( {key: value for key, value in some_iterable}} )

Try to implement this way and if you get in doubt you can comment and ask.

    
10.07.2016 / 18:15