我试图将我的列表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)
每次都覆盖文件的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', '############']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句