删除每行中的双引号(csv writer)

2024-04-27 02:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python3.7将API结果写入CSV文件。问题是在写入文件时,它会向每一行添加双引号(“”)。在

我将格式作为csv传递到API调用,这样我就可以得到csv格式的结果,然后将其写入csv文件,存储到特定位置。 如果有更好的方法,请提出建议。在

这是示例代码。。在

    with open(target_file_path, 'w', encoding='utf8') as csvFile:
        writer = csv.writer(csvFile, quoting=csv.QUOTE_NONE, escapechar='\"')
        for line in rec.split('\r\n'):
            writer.writerow([line])

当我使用escapechar='\"'时,它会在每一列的值处添加(")。在

这是样本记录。。在

^{pr2}$

Tags: 文件csvcsvfile方法代码api示例格式
2条回答

你试过从escapechar='\"'中删除反斜杠吗?这不应该是必需的,因为您对字符串使用单引号。

编辑:来自documentation

A one-character string used by the writer to escape the delimiter if quoting is set to QUOTE_NONE and the quotechar if doublequote is False. On reading, the escapechar removes any special meaning from the following character.

还有退步表:

A one-character string used to separate fields. It defaults to ','

所以它将使用您设置为escapechar的任何值来转义delimeter(,),在本例中是,

如果你不想逃跑,试着让它空着

API提供可以直接写入文件的字符串/字节。在

data = request.get(..).content
open(filename, 'wb').write(data)

如果使用csv.writer,则必须使用csv.reader将字符串/字节转换为Python的数据,然后使用csv.writer将其转换回string/bytes,这样做没有意义。在


如果API发送任何文件:JSONCSVXMLPDF、图像、音频等,也可以使用相同的方法

对于更大的文件,您可以使用chunk/stream中的requests。文件:requests - Advanced Usage

相关问题 更多 >