我正在尝试将几个元组写入一个 csv 文件。
这是我尝试过的:
import csv
out_file = open('csv_write.csv', 'w')
writer = csv.writer(out_file)
writer.writerow((0, 1, 2))
writer.writerow((3, 4, 5))
out_file.close()
这有效,但没有达到预期效果。注意电子表格中的空白行:
在文本编辑器中,文件如下所示:
0,1,2
<blank line>
3,4,5
<blank line>
(共 4 行)
没有这些空白行我怎么写?
最佳答案
csv
模块有自己的行尾处理,并要求以特定方式打开输出文件:
out_file = open('csv_write.csv', 'wb') # Python 2.x
out_file = open('csv_write.csv', 'w', newline='') # Python 3.x
引用 http://docs.python.org/2.7/library/csv.html?highlight=csv#csv.writer :
...it must be opened with the ‘b’ flag on platforms where that makes a difference.
和http://docs.python.org/3.3/library/csv.html?highlight=csv#csv.writer :
...it should be opened with newline=''...
您的空白行是由于 csv
模块的默认“方言”是 excel
。该方言定义 lineterminator='\r\n'
并且这些字符直接写入流。在 Python 2 上以文本模式打开输出文件或在 Python 3 上不使用 newline=''
“在不同的平台上”(Windows) 将所有 \n
翻译成输出流到 \r\n
,结果是 \r\r\n
。这会导致额外的空白行。
关于python - 如何在没有空行的python中在csv文件中写入元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18328133/