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")
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
– drgarcia1986
Where’s the code? Put it on, man.
– Christian Felipe
A went without wanting, I do not know why the editor did not post the link, it tries to put
– Rodrigo Damasceno
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):
- onlyfor 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".– jsbueno