我正试图将失败的值发送到CSV文件,但它只给了我列表中最后一个失败的值。
print(("Foldert"+ "Expectedt"+ "Actualt"+"Result").expandtabs(20))
for key in expected:
expectedCount = str(expected[key])
actualCount = "0"
if key in newDictionary:
actualCount = str(newDictionary[key])
elif expectedCount == actualCount:
result = "Pass"
else:
result = "Fail"
with open('XML Output.csv', 'w',encoding='utf-8', newline="") as csvfile:
header = ['Folder', 'Expected', 'Actual','Result']
my_writer = csv.writer(csvfile)
my_writer.writerow(header)
my_writer.writerow([key, expectedCount, actualCount, result])
csvfile.close()
print((key + "t"+expectedCount+ "t"+actualCount+ "t"+result).expandtabs(20))
print("======================== Data Exported to CSV file ========================")
输出:
文件夹预期实际结果
D2 1 故障
以下是输出:
文件夹预期实际结果
A 2 1失败
B2 1 失败
C2 1失败
D2 1 失败
这是因为每次使用w
的with open
迭代都会覆盖文件,只在文件末尾留下最后一次迭代。您可以使用a
进行追加。
更好的方法可能是创建一个数据结构来保存故障并同时写入文件。试试下面的。如果没有初始数据,我无法测试它,但我想你会得到我想要的。
print(("Foldert"+ "Expectedt"+ "Actualt"+"Result").expandtabs(20))
failures = []
for key in expected:
expectedCount = str(expected[key])
actualCount = "0"
if key in newDictionary:
actualCount = str(newDictionary[key])
elif expectedCount == actualCount:
result = "Pass"
else:
result = "Fail"
csv_row = {
"Folder":key,
"Expected":expectedCount,
"Actual":actualCount,
"Result":"Fail"
}
failures.append(csv_row)
print((key + "t"+expectedCount+ "t"+actualCount+ "t"+result).expandtabs(20))
try:
with open('XML Output.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=failures[0].keys())
writer.writeheader()
for data in failures:
writer.writerow(data)
except IOError:
print('I/O Error on CSV export')
print("======================== Data Exported to CSV file ========================")
编辑:
想添加一个注释,如果您想使用字典写入CSV,DictWriter是一个合适的选择。
https://docs.python.org/3/library/csv.html#csv.DictWriter
每次迭代到达else分支时,都要重新创建csv文件。您需要将with语句移出循环:
import csv
expected = {"a": 1, "b": 2}
newDictionary = {"a": 2, "c": 2}
with open('XML Output2.csv', 'w', encoding='utf-8', newline="") as csvfile:
header = ['Folder', 'Expected', 'Actual', 'Result']
my_writer = csv.writer(csvfile)
my_writer.writerow(header)
for key in expected:
expectedCount = str(expected[key])
actualCount = "0"
if key in newDictionary:
actualCount = str(newDictionary[key])
if expectedCount == actualCount:
result = "Pass"
else:
result = "Fail"
my_writer.writerow([key, expectedCount, actualCount, result])
print((key + "t" + expectedCount + "t" + actualCount + "t" + result).expandtabs(20))
print("======================== Data Exported to CSV file ========================")
另外,请注意,您不需要对使用上下文管理器(with(创建的文件显式调用close((。有关此问题的更多信息,请参阅本文:https://realpython.com/python-with-statement/