将列表写入文本文件

时间:2016-06-16 02:03:51

标签: python list file

使用Windows 10

以下是我的代码示例,其中的问题是:

if choice2 == "d":
    amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " % intBalance))
    newBalance = intBalance + amount

    print "Current balance: %i" %newBalance

    f.close()
    os.remove("accounts.txt")
    f = open("accounts.txt", "a+")

    fileVar.remove(accessedAccount[2])
    fileVar.remove(accessedAccount[1])
    fileVar.remove(accessedAccount[0])

    f.write(accessedAccount[0] + "\n")
    f.write(accessedAccount[1] + "\n")

    newBalance = str(newBalance)
    f.write(newBalance + "\n")

    for item in fileVar:
        f.write("%s\n" %item)
        test = raw_input("Waiting for input")

底部是将列表信息(称为fileVar)写入文本文件(称为f)的代码。它确实将信息写入列表,但它弄乱了我正在制作的程序不会发生的行的顺序,因为该文件必须能够被读回程序以便以后工作。

以下是我的完整上下文代码:

import os
import string

again = "y"
f = open('accounts.txt', 'a+')

fileVar = f.read().splitlines()
print fileVar
accessedAccount = []
data = f.read()

choice = raw_input("What would you like to do? (add/remove a bank account, access a bank account): ")

if choice == "a":
    while again == "y":
        accName = raw_input("Account owner's name: ")
        accType = raw_input("Account type: ")
        accBal = "0"

        f.seek(0, 2)
        f.write(accName + "\n")
        f.write(accType + "\n")
        f.write(accBal)
        f.write("\n")

        again = raw_input("Add another account?: ")

if choice == "a2":
    account = raw_input("What is the name of the account you wish to access?: ")
    for i, line in enumerate(fileVar):
        if account in line:
            for j in fileVar[i:i+3]:
                print j
                accessedAccount.append(j)
    print accessedAccount
    balance = accessedAccount[2]
    intBalance = int(balance)
    print accessedAccount

    choice2 = raw_input("This is your bank account. What would you like to do now? (Withdraw/deposit, exit): ")

    if choice2 == "d":
        amount = int(raw_input("How much money would you like to deposit? Current balance: %i : " %intBalance))
        newBalance = intBalance + amount
        print "Current balance: %i" %newBalance
        f.close()
        os.remove("accounts.txt")
        f = open ("accounts.txt", "a+")
        fileVar.remove(accessedAccount[2])
        fileVar.remove(accessedAccount[1])
        fileVar.remove(accessedAccount[0])
        f.write(accessedAccount[0] + "\n")
        f.write(accessedAccount[1] + "\n")
        newBalance = str(newBalance)
        f.write(newBalance + "\n")
        for item in fileVar:
            f.write("%s\n" %item)
            test = raw_input("Waiting for input")

    if choice2 == "w":
        amount = int(raw_input("How much money would you like to withdraw? Current balanace: %i : " %intBalance))
        newBalance = intBalance - amount
        print "Current Balance: %i" %newBalance
        f.close()
        os.remove("accounts.txt")
        f = open ("accounts.txt", "a+")
        fileVar.remove(accessedAccount[0])
        fileVar.remove(accessedAccount[1])
        fileVar.remove(accessedAccount[2])
        f.write(accessedAccount[0] + "\n")
        f.write(accessedAccount[1] + "\n")
        newBalance = str(newBalance)
        f.write(newBalance + "\n")
        for item in fileVar:
            f.write("%s\n" %item)
            test = raw_input("Waiting for input")

if choice == "r":
    removeChoice = raw_input("What is the name of the account you wish to remove?: ")
    f.close()
    os.remove("accounts.txt")
    f= open("accounts.txt", "a+")
    for i, line in enumerate(fileVar):
        if removeChoice in line:
            for j in fileVar[i:i+3]:
                accessedAccount.append(j)
    fileVar.remove(accessedAccount[0])
    fileVar.remove(accessedAccount[1])
    fileVar.remove(accessedAccount[2])
    for item in fileVar:
        f.write("%s\n" %item)

f.close()
例如,原始文本文件如下所示:

Ryan
Savings
0
John
Chequings
0
Carly
Savings
0

如果用编辑后的信息重新编写,它应该是什么样的,如果300美元被添加到Carly的帐户中:

Carly
Savings
300
Ryan
Savings
0
John
Chequings
0

它看起来像是什么:

Carly
Savings
300
John
Chequings
Ryan
0
Savings
0

提前谢谢你:)

2 个答案:

答案 0 :(得分:0)

不能直接回答您的问题,但有些指针最终可能会让您和其他人更轻松地调试您的代码。

1)功能是你的朋友。看看你是否可以完成小任务并将其分解为各种功能。例如,将某人的余额写入文件可能是一个小功能,您可以称之为:

def write_balance_to_file(account_details):
     ...function code goes here...


account_details = {name:"Ryan", account:"Savings", balance:1000}
write_balance_to_file(account_details)

应该在该功能中处理打开和关闭文件,最好使用:

with open('filename', 'a+') as f:
    f.write("A thing to write")

请注意,执行此操作时无需手动关闭文件。

2)使用字典存储人员的帐户详细信息,而不是列表。多个帐户可以存储为字典列表。这使得它更容易阅读,如:

f.write(accessedAccount[0] + "\n")

变为:

f.write(accessedAccount['name'] + '\n')

然后,您可以将此词典传递给您将创建的write_balance_to_file方法。 :)

3)考虑accounts.txt文件的制表符分隔格式。请记住转义/删除用户输入中的任何选项卡。这样每个帐户都会在一行上。

4)未来对你来说可能有一点点,但要注意单元测试存在,并且是很好的做法。实质上,您可以编写测试(通常使用测试框架,如py.test),在不同的输入条件下测试每个函数/类/模块。任何你不能分解成小的,可测试的代码片段(函数或类)的东西可能都不是好代码。编写测试是识别代码中的错误的好方法,通常有助于澄清您的想法。总是测试!

答案 1 :(得分:0)

对于解决问题的最小变化,这是需要更改的代码:

for i, line in enumerate(fileVar):
    if account in line:
        for j in fileVar[i:i+3]:
            print j
            accessedAccount.append(j)

这会记录哪些条目是accessedAccount的一部分,但稍后您只需删除这些条目的第一个:

    fileVar.remove(accessedAccount[2])
    fileVar.remove(accessedAccount[1])
    fileVar.remove(accessedAccount[0])

但是如果条目与0一样简单,那么它不一定会从正确的位置删除它,所以在pop放置它们时fileVar来自accessedAccount进入for i, line in enumerate(fileVar): if account in line: for j in range(3): print i+j accessedAccount.append(fileVar.pop(i+j)) #break # you probably want to stop checking by this point

fileVar

这会删除accessedAccount中的相关内容,并将它们放在.remove中,这样就可以使用.remove来消除行的顺序,然后显然会将调用注释掉## fileVar.remove(accessedAccount[2]) ## fileVar.remove(accessedAccount[1]) ## fileVar.remove(accessedAccount[0])

$response = new RedirectResponse($this->router->generate('your route'), Symfony\Component\HttpFoundation\Response::HTTP_TEMPORARY_REDIRECT);

这应该可以解决掉错线的直接问题。