python - 如何保存包含记录的列表以打印到文本文件 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)
解决方案
每次覆盖文件的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', '############']
推荐阅读
- php - If 语句的第二部分不起作用
- jmeter - 尝试使用其他语言发送 PUT 请求时出现服务器错误
- validation - 在 redcap 中导入 csv 文件时的自定义数据验证
- html - 如何为进度条 bootsrap 4 分配自定义颜色
- node.js - 会话数据如何存储在服务器端的 NodeJS 中?
- javascript - JavaScript 删除对象属性不在引号中时会出错
- jquery - 根据值中的文本字符串切换表单元素?
- machine-learning - FCN 头是如何对 RetinaNet 的 FPN 特征进行卷积的?
- signal-processing - ADC 中的时间误差
- java - 在 Users 集合中创建一个朋友子集合,Cloud Firestore