如何保存包含记录的列表以打印到文本文件?

2024-05-23 16:01:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将列表strOtherLine写入文本文件,但我只得到列表的最后一条记录,而不是所有记录。所以我说,如果我在列表中得到这3条,我只会得到文本文件中的最后一条记录

 [**********, 'Checking', '0000000000', '############']
 [**********, 'Checking', '0000000000', '############']
 [**********, 'Checking', '0000000000', '############']

代码:

if (strDdtype == "P" and len(strPc_AcctNo.strip()) or strDdtype == "C" or strDdtype == "S"):
       boolHasDirectDepositData = True
       intOtherRecs = intOtherRecs + 1
       boolHasOther = True
       if strDdtype == "S":
            strThisType = "Savings"
       else:
            strThisType = "Checking"
                    
       if strDdtype == "P":
            strThisRoute = strPc_Route
            strThisAcct = strPc_AcctNo
       else:
            strThisRoute = strBankRoute
            strThisAcct = strBankAcct
                        
            
       strOtherLine = [strSsn,strThisType,strThisRoute,strThisAcct]
       print(strOtherLine)
       if boolHasDirectDepositData:
          #===Writing to the text file
          with open(fc_otherfile,'w', newline='') :
              directdep = csv.writer(t, delimiter="\t")
              directdep.writerow(strOtherLine)

Tags: ortrue列表if记录文本文件checkingacctno
1条回答
网友
1楼 · 发布于 2024-05-23 16:01:36

open()中的w模式每次都会覆盖文件(创建一个新的空文件)。您应该使用a模式,在这种情况下,如果文件不存在,脚本将创建一个新文件,但它存在,然后脚本将新行追加到文件中

示例代码:

import csv

strOtherLine = [
    ["**********", "Checking", "0000000000", "############"],
    ["**********", "Checking", "0000000000", "############"],
    ["**********", "Checking", "0000000000", "############"],
]

my_csv_file = "test.csv"


with open("test.csv", "a") as opened_file:
    directdep = csv.writer(opened_file, delimiter="\n")  # Used "\n" for better reading
    directdep.writerow(strOtherLine)

第一次运行后的内容(文件不存在):

['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']

第二次运行后的内容(文件存在):

['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']
['**********', 'Checking', '0000000000', '############']

相关问题 更多 >