简体   繁体   English

Output 枚举 function 到 csv 在 ZA7F5F35426B9274211FC9231B5Z6

[英]Output enumerate function to csv in Python

I am trying to understand how to enumerate through a csv file and output the results to another csv file.我试图了解如何通过 csv 文件和 output 将结果枚举到另一个 csv 文件。 For example, I have a csv file that has 2 columns, group_id and node_id.例如,我有一个 csv 文件,它有 2 列,group_id 和 node_id。 I want to use this csv file, loop through it and output the group_id, node_id and a formatted string that mentions the node_id.我想使用这个 csv 文件,遍历它和 output group_id、node_id 和一个提到 node_id 的格式化字符串。 My code does exactly this when I use the print function however when I attempt to write to another csv file, only the last row is written.当我使用打印 function 时,我的代码正是这样做的,但是当我尝试写入另一个 csv 文件时,只写入最后一行。

Here is my code:这是我的代码:

import csv

with open('input.csv', 'r') as f:

    config_csv = csv.reader(f)

    for row, column in enumerate(config_csv):

        if row == 0:
            continue

        group_id = int(column[0])
        sub_id = column[1]
        node = f"The sub ID for this node is {sub_id}."
        full_output=[group_id, sub_id, node]
        print(full_output)

        with open('output.csv', 'w') as file:
            writer=csv.writer(file)
            writer.writerow(full_output)

csv file (input.csv): csv 文件(输入.csv):

GROUP_ID,SUB_ID
675233,111
877531,222
455632,333

And my print output is:我的打印 output 是:

[675233, 111, 'The sub ID for this node is 111.']
[877531, 222, 'The sub ID for this node is 222.']
[455632, 333, 'The sub ID for this node is 333.']

However my output file (output.csv) only shows the last line:但是我的 output 文件(output.csv)只显示最后一行:

[455632, 333, 'The sub ID for this node is 333.']

What am I doing wrong?我究竟做错了什么? Why doesn't it output the same to the csv file that I see in the print function?为什么 output 与我在打印 function 中看到的 csv 文件不同?

Open both files and write the lines as they are processed.打开这两个文件并在处理它们时写入行。 It's not clear from your incorrect indentation but you are probably writing a new file each time through the loop so only end up with the last line.从您不正确的缩进中不清楚,但您可能每次通过循环都在编写一个新文件,所以只能以最后一行结束。

Also, make sure to use newline='' when opening as per csv documentation :此外,请确保按照csv 文档打开时使用newline=''

import csv

# Need Python 3.10 for parenthesized context manager support.
# Use the following one-liner on older versions.
#with open('input.csv', 'r', newline='') as fin, open('output.csv', 'w', newline='') as fout:
with (open('input.csv', 'r', newline='') as fin,
      open('output.csv', 'w', newline='') as fout):

    reader = csv.reader(fin)
    writer = csv.writer(fout)

    # read and copy header to output
    header = next(reader)
    header.append('COMMENT')
    print(header)
    writer.writerow(header)

    for row in reader:
        node = f"The sub ID for this node is {row[1]}."
        row.append(node)
        print(row)
        writer.writerow(row)

Console output:控制台 output:

['GROUP_ID', 'SUB_ID', 'COMMENT']
['675233', '111', 'The sub ID for this node is 111.']
['877531', '222', 'The sub ID for this node is 222.']
['455632', '333', 'The sub ID for this node is 333.']

output.csv: output.csv:

GROUP_ID,SUB_ID,COMMENT
675233,111,The sub ID for this node is 111.
877531,222,The sub ID for this node is 222.
455632,333,The sub ID for this node is 333.


As said by the comment of Barmar.正如 Barmar 的评论所说。

Opening the file in w mode empties the file.以 w 模式打开文件会清空文件。 Don't reopen the file in the loop, open it once at the beginning and write a row to it each time through the loop不要在循环中重新打开文件,在开始时打开一次,每次循环写入一行

So I see basically two options.所以我基本上看到了两种选择。
1- You can use open without "with", and it will be the same result 1-你可以使用不带“with”的open,结果是一样的

f = open("demofile.txt", "r")

instead of代替

with open('input.csv', 'r') as f:

See more看更多

2- You can store all the data you are reading and then write it in the other csv file 2-您可以存储您正在读取的所有数据,然后将其写入另一个 csv 文件

For example, you could create a class:例如,您可以创建 class:

class GroupData :
   group_id = 0
   sub_id = 0
   node = ""

And then create a list of groupdata objets.然后创建一个 groupdata 对象列表。
Add element in your list while reading the first file.在读取第一个文件时在列表中添加元素。
Then read all the elements in another loop and write in the other file.然后读取另一个循环中的所有元素并写入另一个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM