Python csv 写文件时默认的空行最简单的处理方式

def write_module(infilename):
    header = ['name' , 'score']
    stu1 = ['frank', '61']
    stu2 = ['bill', '59']
    
    out_csv = open(infilename, 'wt+')
    csv_writer = csv.writer(out_csv, dialect='excel')
    csv_writer.writerows([header,stu1,stu2])
    print('-------> Done')

使用Python csv 写入文件时,发现每行数据之间会多一个空行

网上查了资料,最简单有效的解决方案就是在打开文件时,设定newline参数为‘’

out_csv = open(infilename, 'wt+', newline='')

即可解决空行的问题。

附:如果想知道为啥加上newline=''就不会空一行,感兴趣的同志们可以参考一下源码说明(On input是写入):

newline controls how universal newlines works (it only applies to text mode). It can be None, '', '/n', '/r', and '/r/n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '/n', '/r', or '/r/n', and these are translated into '/n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '/n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '/n', no translation takes place. If newline is any of the other legal values, any '/n' characters written are translated to the given string.

猜你喜欢

转载自my.oschina.net/frankwu/blog/1796855
今日推荐