为什么在使用python 3.6.4编写csv文件时跳过一行?
我在python 3.6.4中有一个简单的程序,可以在csv文件中写入数据。当我使用excel 2010打开文件test.csv时,我发现结果是这样写的: 以下是节目:为什么在使用python 3.6.4编写csv文件时跳过一行?,python,csv,writing,Python,Csv,Writing,我在python 3.6.4中有一个简单的程序,可以在csv文件中写入数据。当我使用excel 2010打开文件test.csv时,我发现结果是这样写的: 以下是节目: import csv lol = [(1,2,3),(4,5,6),(7,8,9)] item_length = len(lol[0]) with open('test.csv', 'w') as test_file: file_writer = csv.writer(test_file) for i in r
import csv
lol = [(1,2,3),(4,5,6),(7,8,9)]
item_length = len(lol[0])
with open('test.csv', 'w') as test_file:
file_writer = csv.writer(test_file)
for i in range(item_length):
file_writer.writerow([x[i] for x in lol])
将newline=''
添加到open()
参数以防止出现这种情况
with open('test.csv', 'w', newline='') as test_file:
file_writer = csv.writer(test_file)
for i in range(item_length):
file_writer.writerow([x[i] for x in lol])
解决方案是在构造函数中指定“lineterminator”参数,但它们是否确实存在于CSV文件中?听起来Excel使用的换行约定与文件中实际存在的不同。否,文件处于w模式,因此它是新的。文件为空,文件中没有任何内容file@YassinMohamadi不客气!请接受我的回答,如果它是你正在寻找的for@YassinMohamadi:的第三行(以及
csv.reader
)明确指出:“如果csvfile是文件对象,则应使用newline='
打开它。”