Py学习  »  Python

在python csv writer中用0或null填充空列值

Avocado • 6 年前 • 1781 次点击  

我正在用python创建csv文件,并使用django模型和sql server编写数据。数据库中有一些空值。当我编写csv文件时,它将空值写为“”(空)。如何在csv中用“null”或“0”填充空字段?

with open(f'{store_data}/test.csv', 'w', encoding='utf-8') as dataFile:
    task_data = MonitorItem.objects.all()
    wr = csv.writer(dataFile)
    # wr.writerow(taskHeaders)
    for t in task_data:
        wr.writerow([t.x, t.y, t.z])
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41100
文章 [ 1 ]  |  最新文章 6 年前
JPG
Reply   •   1 楼
JPG    6 年前

试试这样的东西,

with open(f'{store_data}/test.csv', 'w', encoding='utf-8') as dataFile:
    task_data = MonitorItem.objects.all()
    wr = csv.writer(dataFile)
    # wr.writerow(taskHeaders)
    for t in task_data:
        x = t.x or "0"
        y = t.y or "0"
        z = t.z or "0"
        wr.writerow([x, y, z])

这里 x = t.x or "0" 是对…的渴望

if t.x:
    x = t.x
else:
    x = "0"

希望这有帮助!!