相关疑难解决方法(0)

如何将数据写入csv格式为字符串(而不是文件)?

我想将数据[1,2,'a','He said "what do you mean?"']转换为csv格式的字符串.

通常人们可以使用csv.writer()它,因为它处理所有疯狂的边缘情况(逗号转义,引用标记转义,CSV方言等).捕获是csv.writer()期望输出到文件对象,而不是字符串.

我目前的解决方案是这个有点hacky函数:

def CSV_String_Writeline(data):
    class Dummy_Writer:
        def write(self,instring):
            self.outstring = instring.strip("\r\n")
    dw = Dummy_Writer()
    csv_w = csv.writer( dw )
    csv_w.writerow(data)
    return dw.outstring
Run Code Online (Sandbox Code Playgroud)

任何人都可以提供更优雅的解决方案,仍能很好地处理边缘情况吗?

编辑:这是我最终如何做到这一点:

def csv2string(data):
    si = StringIO.StringIO()
    cw = csv.writer(si)
    cw.writerow(data)
    return si.getvalue().strip('\r\n')
Run Code Online (Sandbox Code Playgroud)

python csv string

96
推荐指数
4
解决办法
8万
查看次数

Write a header at every logfile that is created with a time-rotating logger

I've made a time-rotating logger which creates a new logfile at midnight. In my logfile I want to write a header at the top of every file. I'm looking for an efficient way to call a function which writes this header to the logfile upon the moment that the file is created.

import logging
from logging.handlers import TimedRotatingFileHandler

# create time-rotating log handler
logHandler = TimedRotatingFileHandler(logfile, when='midnight')

# create logger
self.log = logging.getLogger('MyTimeRotatingLogger')
self.log.addHandler(logHandler)
Run Code Online (Sandbox Code Playgroud)

python logging

5
推荐指数
1
解决办法
2026
查看次数

标签 统计

python ×2

csv ×1

logging ×1

string ×1