使用Python的csv.writer的时候怎样包含双引号

这也是个现实的需求,发现用Excel另存为csv的时候是没有双引号的(看了一些人写的博客,感觉也没说清楚),没办法只能用python,但是默认用csv.writer的时候,entry之间也是没有双引号的,搜了一下,发现还是官网说得最清楚,很多朋友的博客都写得太混乱了:

具体来讲,csv.reader和csv.writer的说明和示例为:

csv — CSV File Reading and Writing — Python 3.11.1 documentation

csv — CSV File Reading and Writing — Python 3.11.1 documentation

可以看到还是很好理解的,我只说一下writer的相关参数:

网页中的这个例子已经说得很明白了:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

其中这些Dialects and Formatting Parameters可以在对应网页看到,我们需要关心的就是这里的quoting:

Dialect.quoting

Controls when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants (see section Module Contents) and defaults to QUOTE_MINIMAL.

可以看到这个参数默认使用QUOTE_MINIMAL. 链接在这里:csv — CSV File Reading and Writing — Python 3.11.1 documentation

在其附近可以看到其他选项如下:

The csv module defines the following constants:

csv.QUOTE_ALL

        Instructs writer objects to quote all fields.

csv.QUOTE_MINIMAL

        Instructs writer objects to only quote those fields which contain special characters such         as delimiterquotechar or any of the characters in lineterminator.

csv.QUOTE_NONNUMERIC

        Instructs writer objects to quote all non-numeric fields.

        Instructs the reader to convert all non-quoted fields to type float.

csv.QUOTE_NONE

        Instructs writer objects to never quote fields. When the current delimiter occurs in         output data it is preceded by the current escapechar character. If escapechar is not         set, the writer will raise Error if any characters that require escaping are encountered.

        Instructs reader to perform no special processing of quote characters.

要使所有entry都有双引号,改成csv.QUOTE_ALL即可。

另外,要解决csv.writer写的时候产生空行的问题,可以将newline=''(指定为空),例如下面我自己的代码:

roster_out_file=open(roster_file_name+'_final'+'.csv','w',newline='')
writer=csv.writer(roster_out_file,quoting=csv.QUOTE_ALL)

定义好writer之后写每一行就可以了:writer.writerow(row)

猜你喜欢

转载自blog.csdn.net/qysh123/article/details/128261427