header 在 csv 文件中每隔一行打印一次

header in csv file printing every other line

我解决这个问题的时间太长了,请向我解释为什么 header 在我的输出 csv 中不断重复。

我有一个包含以下数据的输入 csv:

  1. 名字,房子
  2. “雅培,汉娜”,赫奇帕奇
  3. “贝尔,凯蒂”,格兰芬多
  4. “骨头,苏珊”,赫奇帕奇
  5. “启动,特里”,拉文克劳

问题需要颠倒姓氏和名字,将姓名分成两列,并为输出 csv 创建一个包含 3 列的新 header。这是我拥有的:

    while True:
        try:
            # open file
            with open(sys.argv[1]) as file:
                # make reader
                reader = csv.reader(file)
                # skip first line (header row)
                next(reader)
                # for each row
                for row in reader:
                    # identify name
                    name = row[0]
                    # split at ,
                    name = name.split(", ")
                    # create var last and first, identify var house
                    last = name[0]
                    first = name[1]
                    house = row[1]


                    # writing the new csv
                    with open(sys.argv[2], "a") as after:
                        writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])

                        # HEADER ONLY NEEDS TO OCCUR ONCE
                        writer.writeheader()
                        writer.writerow({"first": first, "last": last, "house": house})
                sys.exit(0)

我的输出 csv:

  1. 第一个,最后一个,房子
  2. 汉娜、雅培、赫奇帕奇
  3. 第一个,最后一个,房子
  4. 凯蒂、贝尔、格兰芬多
  5. 第一个,最后一个,房子
  6. 苏珊,骨头,赫奇帕奇

我试过删除 while 循环,取消缩进和缩进,用 header 名称手动写一行(这会导致错误)。请帮忙。谢谢!

您可以添加一个变量来保存是否打印了 header,例如 write_header

while True:
    try:
        write_header = True
        # open file
        with open(sys.argv[1]) as file:
            # make reader
            reader = csv.reader(file)
            # skip first line (header row)
            next(reader)
            # for each row
            for row in reader:
                # identify name
                name = row[0]
                # split at ,
                name = name.split(", ")
                # create var last and first, identify var house
                last = name[0]
                first = name[1]
                house = row[1]


                # writing the new csv
                with open(sys.argv[2], "a") as after:
                    writer = csv.DictWriter(after, fieldnames=["first", "last", "house"])

                    # HEADER ONLY NEEDS TO OCCUR ONCE
                    if write_header:
                        writer.writeheader()
                        write_header = False
                    writer.writerow({"first": first, "last": last, "house": house})
            sys.exit(0)

看看我是怎么用的write_header

另一方面,您可以重构代码以在 for 循环之前打开 csv 编写器,在那里写入 headers,然后像现在一样写入值,而无需重新打开每次要写一行的文件