【问题标题】:why skipping a line when writing in csv file using python 3.6.4?为什么在使用 python 3.6.4 写入 csv 文件时跳过一行?
【发布时间】:2018-04-03 21:24:57
【问题描述】:

当我使用 excel 2010 打开文件 test.csv 时,我在 python 3.6.4 中有这个简单的程序在 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 range(item_length):
    file_writer.writerow([x[i] for x in lol])

【问题讨论】:

  • 但它们真的存在于 CSV 文件中吗?
  • 听起来 Excel 使用的换行约定与文件中实际存在的换行约定不同。
  • 不,文件是 w 模式,所以它是新的
  • 文件为空文件中没有任何内容

标签: python csv writing


【解决方案1】:

将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])

【讨论】:

  • @YassinMohamadi 欢迎您!如果您正在寻找,请接受我的回答
  • @YassinMohamadi:the docs for csv.writer(以及csv.reader)的第三行清楚地表明了这一点:“如果 csvfile 是文件对象,则应使用newline='' 打开它”跨度>
【解决方案2】:

解决方法是在构造函数中指定“lineterminator”参数

【讨论】:

    猜你喜欢
    • 2019-01-01
    • 2021-06-28
    • 2016-11-16
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多