使用python从文件中删除记录

时间:2017-03-30 17:01:11

标签: python

我正在python 3.6中创建一个非常基本的银行记录程序。我创建了一个文件“accounts.txt”,用户可以在其中添加帐户 - 名称,帐号,余额。添加后,文件看起来像这样:

213123 | dgfdg | 21312.0
123124 | vxcvx | 213123.0
123123 | sfsdf | 123123.0

列分别代表帐号,名称,余额。

我想从此文件中删除特定记录。我考虑不了。作为要删除的记录的输入。我只是想不通怎么做。例如,如果用户输入213123,则应删除整个记录。

同一案例中的另一个问题 - 当我要求用户输入他们的帐号,姓名,余额时,我想扫描“accounts.txt”并且如果帐号已经存在,则产生错误而不是创建错误新纪录。避免重复的帐号。

我是python的新手,这是一个基本的程序所以请不要建议使用mysql或mariadb。 :d

def account_set():
    accno = int(input("Enter Account Number \t"))
    name = str(input("Enter Name \t"))
    balance = float(input("Enter Balance \t"))
    return accno, name, balance

def new():
    account = open("accounts.txt", "a+")
    info = account_set()
    account.seek(0, 2)
    for items in info:
        account.write("{0:<25} {1}".format(items, "|"))
    account.write("\n")
    account.close()

def delete():        
    accno = (input("Enter Account number to delete"))
    file = open("accounts.txt", "r+")


print("""
Please choose any one of the Following Options: \n \n
1. New Account \n
2. Delete Account \n
3. Exit
""")

x = True
while x:
    user_input = int(input("Enter an option \t"))
    if user_input == 1:
        new()
    elif user_input == 2:
        delete()
    elif user_input == 3:          
        print("Thank you for banking with us.")
        x = False
    else:
        print("Invalid Choice")

1 个答案:

答案 0 :(得分:0)

执行此操作的一种可能方法是询问用户输入并查看其编号。如果数字是213123,那么您可以使用此代码:

filename.seek(0)
filename.truncate()

上面的代码将删除整个文件。

此SO帖子解释了如何完美删除单行:Deleting a specific line in a file (python)

要查看是否存在帐号,您可以阅读如下文件:

 f = open("filename.txt").readlines()
 f = [i.strip('\n') for i in f]
 file = [map(int, i.split()) for i in f]
 #then, you can loop through file and see if the account number exists:
 #account numbers are first in the list, so you can make a list of them
 account_numbers = [i[0] for i in file]
 number = 123456
 if number in account_numbers:
     print "account number ", number, " all ready exists"

 else:
     print "account number", number, " does not exist"