如执行下面的代码:
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)
原文地址:https://www.cnblogs.com/mrlayfolk/p/12401561.html
时间: 2024-10-09 08:24:15