将值打印到CSV(Python)

wxclj1h5  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(172)

我尝试将失败的值发送到CSV文件,但它只给我列表中最后一个失败的值。

print(("Folder\t"+ "Expected\t"+ "Actual\t"+"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 ========================")

输出:

文件夹预期实际结果
D 2 1未通过

以下是输出结果:

文件夹预期实际结果
A 2 1失败
B 2 1失败
C 2 1故障
D 2 1未通过

pftdvrlh

pftdvrlh1#

这是因为每次使用wwith open迭代都会覆盖文件,只在文件末尾留下最后一次迭代。
一个更好的方法是创建一个数据结构来保存故障并同时写入文件。给予下面的方法。没有初始数据我无法测试它,但我想你会得到我想要的。

print(("Folder\t"+ "Expected\t"+ "Actual\t"+"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

4uqofj5v

4uqofj5v2#

在每次迭代遇到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/

相关问题