簡體   English   中英

使用 python 寫入 csv 文件時出錯

[英]error while writing to csv file with python

我正在嘗試逐行寫入一些 output 到 csv 文件

這是我嘗試過的:

import csv

today = datetime.datetime.now().date()
filter = "eventTimestamp ge {}".format(today)
select = ",".join([
    "eventTimestamp",
    "eventName",
    "operationName",
    "resourceGroupName",
])

activity_logs = client.activity_logs.list(
    filter=filter,
    select=select
)   

with open(r"C:\scripts\logs.csv", 'w', newline='') as f:
    for log in activity_logs:
        result = (" ".join([
            str(log.event_timestamp),
            str(log.resource_group_name),
            log.event_name.localized_value,
            log.operation_name.localized_value
        ]))
        f.writerow(result)

它的拋出錯誤:

AttributeError: '_io.TextIOWrapper' object has no attribute 'writerow'

我該如何修復這個錯誤,可能是任何其他模塊?

錯誤來自以下行:

f.writerow(result)

它告訴您 f object 沒有名為 writerow 的 function。

正如 Jannes 評論的那樣,改用 write function :

f.write(result)

這個:

with open(r"C:\scripts\logs.csv", 'w', newline='') as f:

正在創建文本文件句柄。 您需要使用f創建csv.writer然后您可以使用writerow ,即:

import csv
...
with open(r"C:\scripts\logs.csv", 'w', newline='') as f:
    writer = csv.writer(f)
    for log in activity_logs:
        result = (str(log.event_timestamp),str(log.resource_group_name),log.event_name.localized_value,log.operation_name.localized_value)
        writer.writerow(result)

您可能會在 PyMOTW-3 的 csv 文章中找到有用的用法示例

CSV.writer 當你試圖寫入 CSV 時需要。然后代碼可以

import csv

today = datetime.datetime.now().date()
filter = "eventTimestamp ge {}".format(today)
select = ",".join([
    "eventTimestamp",
    "eventName",
    "operationName",
    "resourceGroupName",
])

activity_logs = client.activity_logs.list(
    filter=filter,
    select=select
)   

with open(r"C:\scripts\logs.csv", 'w', newline='') as file:
    f=csv.writer(file)
    for log in activity_logs:
        result = (str(log.event_timestamp),
            str(log.resource_group_name),
            log.event_name.localized_value,
            log.operation_name.localized_value)
        f.writerow(result)

當打開csv.writer文件后添加 csv.writer 時,它將正常工作而不會出現 TextIOwrapper 錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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