Problems with python code in file i/o

Asked

Viewed 170 times

4

Hello, I’m beginner in python, I’m programming in 3.5.1, I was doing a snippet of code that reads and then removes 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")

http://pastebin.com/BHdnKSQj

And it is deleting the entire file instead of erasing the file and putting all the lines except the one that should be erased. (the program should do this because I don’t know how to delete a text directly in the file)

  • Please post the code to see what might be wrong

  • Where’s the code? Put it on, man.

  • A went without wanting, I do not know why the editor did not post the link, it tries to put

  • I don’t have time to consider ra Gora - but two quick tips: (1) in fact it is impossible to "delete a little directly inside a text file"- just think, and you will see that there is no way this can happen directly without having a code like what you want. (2) In Python, the "for" always prefixes a sequence - if you use with a list, there is no need for these while i < len(p): - only for line in p ; (3) Even so, there is no need for these post-changes in the list: transform already when reading the file the first time. See the method "split".

1 answer

2


I made a slightly more simplified 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 the contents of the dictionary in the text file (only the values)

  • At the end where it is checked whether this script is what is being run by python, I read the file, 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), remove that record from the dictionary and rewrite the file.

Some "languages" that may be news to you:

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

  • list comprehensions and Dict comprehensions: basically I simplified a couple 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 doubts arise you can comment and ask.

  • Thanks, but one thing I still don’t understand there was the format

  • The format is a string class method that is used to format strings, for a look at this link, has an excellent tutorial https://mkaz.tech/python-string-format.html

Browser other questions tagged

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