【问题标题】:CSV writer goes to next line for each input valueCSV 写入器针对每个输入值转到下一行
【发布时间】:2017-12-11 10:45:04
【问题描述】:

我是 Python 新手。我正在尝试在 CSV 文件中写入数字。第一个数字构成行的第一个元素。第二个数字第二个,然后应该开始一个新行。但是,我的代码的工作方式不是将第二个元素添加到同一行,而是创建一个新行。

比如我想要的是:

a1,b1
a2,b2

但我得到的是:

a1
b1
a2
b2

我使用循环将值连续写入 CSV 文件:

n = Ratio # calculated in each loop
with open('ex1.csv', 'ab') as f:
    writer = csv.writer(f)
    writer.writerow([n])
    ...

m = Ratio2 # calculated in each loop
with open('ex1.csv', 'ab') as f:
    writer = csv.writer(f)
    writer.writerow([m])

我希望结果格式为

n1,m1
n2,m2

【问题讨论】:

  • 然后将nm连接在一起,即writer.writerow([n, m])
  • 您可能需要将分隔符指定为','
  • Clomplete minimal example 将有助于更轻松地重现您的问题。
  • 您每次都打开文件并附加到它 - 一旦退出循环就打开它。将您所有的 n s 收集到您要写入的每一行的列表中,一旦该行完全在列表中,请使用 writer.writerow( yourList ) - 它会自动写入列表的每个元素以及其后面的分隔符。

标签: python csv newline


【解决方案1】:

写入文件然后读回并打印的示例:

import csv

with open('ex1.csv', 'w') as f: # open file BEFORE you loop
    writer = csv.writer(f)      # declare your writer on the file

    for rows in range(0,4):     # do one loop per row
        myRow = []              # remember all column values, clear list here
        for colVal in range(0,10):   # compute 10 columns
            m = colVal * rows        # heavy computing  (your m or n)
            myRow.append(m)          # store column in row-list

        writer.writerow(myRow)  # write list containing all columns 

with open('ex1.csv', 'r') as r:  #read it back in 
    print(r.readlines())         # and print it   

输出:

['0,0,0,0,0,0,0,0,0,0\r\n', '0,1,2,3,4,5,6,7,8,9\r\n', '0,2,4,6,8,10,12,14,16,18\r\n', '0,3,6,9,12,15,18,21,24,27\r\n'] 

翻译成一个文件

0,0,0,0,0,0,0,0,0,0
0,1,2,3,4,5,6,7,8,9
0,2,4,6,8,10,12,14,16,18
0,3,6,9,12,15,18,21,24,27

您还可以将每个行列表(通过myList[:] 复制)填充到另一个列表中,然后使用writer.writerows([ [1,2,3,4],[4,5,6,7] ]) 一次性写入所有行。

请参阅:https://docs.python.org/2/library/csv.html#writer-objectshttps://docs.python.org/3/library/csv.html#writer-objects

【讨论】:

    猜你喜欢
    • 2016-12-10
    • 2012-01-30
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多