将数据写入CSV文件时出现错误

时间:2019-02-05 16:28:10

标签: python-2.7

def write_hms(hms):
    try:
    with open(FILENAME, "w", newline="") as file:
    writer = csv.writer(file,delimiter='|')
    writer.writerows(hms)

    except OSError as e:
        print(type(e), e)
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()

获取错误:

  

<class '_csv.Error'>可迭代,而不是int
  终止程序。

1 个答案:

答案 0 :(得分:0)

您没有正确缩进代码,但是如果我复制代码,正确缩进代码并指定您未定义的变量(例如hmsFILENAME),则代码可以正常运行

import sys
import csv

FILENAME = 'test.csv'


def write_hms(hms):
    try:
        with open(FILENAME, "w", newline="") as file:
            writer = csv.writer(file,delimiter='|')
            writer.writerows(hms)
    except OSError as e:
        print(type(e), e)
        sys.exit(1)
    except Exception as e:
        print(type(e), e)
        sys.exit(1)


write_hms(['Spam'] * 5 + ['Baked Beans'])

您收到的错误提示您没有像csv编写器所期望的那样传递“可迭代”,而是传递了int。因此,问题很可能与您在hms中传递的输入没有显示。

如果这不能回答您的问题,请提供完整的最小示例。