簡體   English   中英

Output 枚舉 function 到 csv 在 ZA7F5F35426B9274211FC9231B5Z6

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM