首页 > 解决方案 > 如何保存包含记录的列表以打印到文本文件 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)

标签: pythonpython-3.x

解决方案


每次覆盖文件的w模式(创建一个新的空文件)。open()您应该使用该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', '############']

推荐阅读