[英]Output enumerate function to csv in Python
我试图了解如何通过 csv 文件和 output 将结果枚举到另一个 csv 文件。 例如,我有一个 csv 文件,它有 2 列,group_id 和 node_id。 我想使用这个 csv 文件,遍历它和 output group_id、node_id 和一个提到 node_id 的格式化字符串。 当我使用打印 function 时,我的代码正是这样做的,但是当我尝试写入另一个 csv 文件时,只写入最后一行。
这是我的代码:
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 文件(输入.csv):
GROUP_ID,SUB_ID
675233,111
877531,222
455632,333
我的打印 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.']
但是我的 output 文件(output.csv)只显示最后一行:
[455632, 333, 'The sub ID for this node is 333.']
我究竟做错了什么? 为什么 output 与我在打印 function 中看到的 csv 文件不同?
打开这两个文件并在处理它们时写入行。 从您不正确的缩进中不清楚,但您可能每次通过循环都在编写一个新文件,所以只能以最后一行结束。
此外,请确保按照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)
控制台 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:
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.
正如 Barmar 的评论所说。
以 w 模式打开文件会清空文件。 不要在循环中重新打开文件,在开始时打开一次,每次循环写入一行
所以我基本上看到了两种选择。
1-你可以使用不带“with”的open,结果是一样的
f = open("demofile.txt", "r")
代替
with open('input.csv', 'r') as f:
2-您可以存储您正在读取的所有数据,然后将其写入另一个 csv 文件
例如,您可以创建 class:
class GroupData :
group_id = 0
sub_id = 0
node = ""
然后创建一个 groupdata 对象列表。
在读取第一个文件时在列表中添加元素。
然后读取另一个循环中的所有元素并写入另一个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.