python-去掉写入csv文件的多余的一行空白行

如执行下面的代码:

 1 import csv
 2 
 3 if __name__ == "__main__":
 4 
 5     content1 = ['hello']
 6     content2 = ['world']
 7 
 8     with open('test.csv', 'w') as f:
 9         writer = csv.writer(f)
10         writer.writerow(content1)
11         writer.writerow(content2)

打开test.csv文件查看,如下图:

 可以看到,多了一行空白行,解决方式如下:

如果使用的python3:

 1 import csv
 2 
 3 if __name__ == "__main__":
 4 
 5     content1 = ['hello']
 6     content2 = ['world']
 7 
 8     with open('test.csv', 'w', newline='', encoding='utf-8-sig') as f:
 9         writer = csv.writer(f)
10         writer.writerow(content1)
11         writer.writerow(content2)

如果使用的python2:

 1 import csv
 2 
 3 if __name__ == "__main__":
 4 
 5     content1 = ['hello']
 6     content2 = ['world']
 7 
 8     with open('test.csv', 'wb') as f:
 9         writer = csv.writer(f)
10         writer.writerow(content1)
11         writer.writerow(content2)
posted @ 2020-03-03 12:24  zhengcixi  阅读(3958)  评论(0编辑  收藏  举报
回到顶部