Считывает данные, которые были удалены из файла (Python) [закрыто]Python

Программы на Python
Ответить
Anonymous
 Считывает данные, которые были удалены из файла (Python) [закрыто]

Сообщение Anonymous »

Я написал программу телефонной книги на Python, и в программе есть возможность добавлять, удалять, просматривать контакты, искать, загружать контакты, сохраненные в файле, и когда вы добавляете контакт, он сохраняется в файле .txt< /p>
Проблема в том, что при вводе дубликата контакта выполняется функция overwrite, отвечающая за перезапись файла. Он выполняет свою работу правильно, но когда вы позже удаляете контакт и вводите его снова, выполняется функция перезаписи и сообщает, что контакт сохранен в файле.

Код: Выделить всё

from os import stat,path
directory={}

def reset():
if stat("phone_book.txt").st_size != 0:
open('phone_book.txt', 'w').close()
directory.clear()
print("Successfully Reseted")
return
print("This file is empty")

def Welcome():
print("Welcome to Phone Book")
print("-"*15)

def is_valid_number(number):
return number.isdigit() and len(number) == 11 and number.startswith("09")

def get_num():
while True:
number=input("Enter Number : ")
if is_valid_number(number) and number not in directory.values():
return number
print("Invalid input , number less/more Than 11 , its Duplicate ")
print("-"*15)

def get_names():
while True:
name=input("Enter Name : ")
if name.isalpha() and name not in directory.keys():
return name
print("Invalid Input , Its Duplicate")
print("-"*15)

def add_con():
name=get_names()
number=get_num()
directory[name]= number
save()
return directory

def remove_con():
if directory != {}:
while True:
rem=input("Which One should be deleted ? ")
if rem.isalpha() and rem in directory.keys() :
print(f"{rem} Successfully Deleted")
del directory[rem]
save()
return directory
print("It not in list please try again")
exit_app=input("You wanna Exit From this category ? ")
if exit_app == "yes":break
print("-"*15)
print("-"*15)
print("This list is empty")

def search():
if directory != {}:
while True:
sear=input("Search Name : ")
if sear.isalpha() and sear in directory.keys():
return print(f"{sear} : {directory[sear]}")
print("It not in list please try again")
exit_app=input("You wanna Exit From this category ? ")
if exit_app == "yes":return
print("-"*15)
print("This list is empty")

def list_numbers():
if directory != {}:
for na,nu in directory.items():
print(f"{na} : {nu}")
return
print("This list is empty")

def checkfile(na):
with open("phone_book.txt","r") as book:
return na not in book.read()

def find_number(file_path, search_string):
with open(file_path, 'r') as file:
for line in file:
if search_string in line:
return line

def over_write(name,new_number):
search_text = find_number("phone_book.txt",name).strip()
replace_text = f"'{name}' : '{new_number}'"
with open('phone_book.txt', 'r') as file:
data = file.read()
data = data.replace(search_text, replace_text)

with open('phone_book.txt', 'w') as file:

file.write(data)

print("Contact replaced")

def save():
with open("phone_book.txt","a") as book:
for na,nu in directory.items():
if checkfile(na):
book.write(f"'{na}' : '{nu}'\n,")
print("Successfully Saved")
else:
print("-"*15)
overwrite=input("This name are exist in file.  You can see this contact but is not been saved.\nif you want over write Enter Yes :").lower()
if overwrite == "yes":
over_write(na,nu)
else:
print("If Contact don't be save and you load contacts file , this contact be deleted")
return
return

def load():
if   path.exists("phone_book.txt")and stat("phone_book.txt").st_size != 0:
from ast import literal_eval as la
with open("phone_book.txt","r") as book:
f=book.read()
f="{"+ f.strip() +"}"
directory.update(la(f))
print("Successfully Loaded")
return
print("File is empty/not Exist")

def start():
Welcome()
while True:
print("You can Chose With this Commands : (add/delete/see/search/exit/load/reset) ")
user_choice=input("What you want do ( add contacts / delete contact / see contacts / search contacts / load saved result / reset result) : ").lower()
if user_choice in ["add","delete","see","search","exit","reset","load"]:
print("-"*15)
match user_choice:
case "add":add_con()
case "delete":remove_con()
case "see": list_numbers()
case "search":search()
case "load":load()
case "reset":reset()
case "exit":return
else :print("Invalid input")

print("-"*15)

start()
Я попробовал искусственный интеллект, но он не сработал, я изменил и отладил функцию over_write, но она не сработала.

Подробнее здесь: https://stackoverflow.com/questions/793 ... ile-python
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»