[英]Data logging not happening with required rate using CSV library for python
[英]How to write to a CSV using Python logging library?
我正在嘗試使用 Python 中的日志庫將字符串列表寫入 CSV 日志文件
記錄器創建:
export_logger = logging.getLogger('exportLogger')
export_logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('export_log.csv',mode='w')
export_logger.addHandler(file_handler)
export_logger.info(",".join(['status', 'view', 'filename', 'stdout', 'stderr', 'time']))
記錄:
column_list = [status, view, filename, out, err, current_time]
message = ",".join([str(item) for item in column_list])
export_logger.info(message)
我的問題是,如果任何字符串包含換行符或逗號,它會破壞 output。 我可以用引號將它們括起來,但是如果它們包含引號,它就會中斷。 我可以逃避這些,但我寧願不重寫代碼來解析 CSV 文件寫入的所有邊緣情況。 有沒有好的方法來處理這個?
有沒有辦法輕松清理字符串以寫入 CSV? 我可以這樣做: 如何將數據作為字符串(不是文件)寫入 csv 格式? 但這似乎非常迂回且難以理解。
I'm only using the logging library because I thought that was best practice, but if it can't handle CSV formatting I may as well just open a module level CSV file and write lines to it using the python csv library, right?
logging
庫主要用於臨時運行時/診斷/調試輸出
應該更直接地處理預期/預期的輸出(這似乎是您所追求的) - 在您的情況下,我建議直接打開輸出文件,包裝在csv.writer
,然后根據需要調用writerow
例如:
import csv
output = csv.writer(open('export_log.csv', 'w'))
output.writerow(['status', 'view', 'filename', 'stdout', 'stderr', 'time'])
for foo in bar:
# do work
output.writerow([status, view, filename, out, err, current_time])
請注意, File
對象也是“上下文管理器”,因此這樣做可能有意義:
with open('export_log.csv', 'w') as fd:
output = csv.writer(fd)
…
如果你想確保文件被適當地關閉
如果您想要一個用於大型應用的專用記錄器 class。 您可以創建單獨的對象來記錄多個單獨的文件。 我建議使用pandas
庫,因為它更快且無錯誤。
import pandas as pd
class csvLogger:
def __init__(self, filename):
self.count = 1
self.filename = filename
def __call__(self, named_dict):
df = pd.DataFrame(named_dict, index=[self.count])
df.to_csv("./results/{}.csv".format(self.filename), mode='a', header=self.count == 1)
如您所見,class 將 append 新數據添加到 csv 文件中的新行。 您可以從下面的代碼片段中獲得提示。
mycsvLogger = csvLogger("file.csv")
data = {"x": 1, "y": 2}
mycsvLogger(data)
這應該是許多高級 csv 日志記錄應用程序的通用代碼。 享受:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.