将一个元组写入CSV多行

时间:2018-11-14 15:55:19

标签: python

所以,我有一个python元组。我正在尝试将其写入CSV文件。到目前为止,我可以写入CSV,但是我所有的数据都显示在一行中。谁能告诉我如何将其转换为列?例如,这是我的CSV中一行中的数据。

100 0.01 11139155 5569534 0.499996 NO SYNC 555 0.01 2306110 1153050 0.499998 NO SYNC 333 0.22 3434535 4446466 0.453535 NO SYNC

我想要做的是,我希望以一种方式组织该元组,使其在每次无同步后都移至下一行。

100 0.01 11139155 5569534 0.499996 NO SYNC
555 0.01 2306110 1153050 0.499998 NO SYNC
333 0.22 3434535 4446466 0.453535 NO SYNC

这是我的剧本

with open ('File path') as f:
     writer = csv.writer(f, delimiter = ',')
     writer.writerow(results_t1)
f.close()

results_t1是我的输入元组。

我的输入元组看起来像这样:

(100, 0.01, 11139155, 5569534, 0.499996094856387, 'NO SYNC', 555, 0.01, 2306110, 1153050, 0.499997831846703, 'NO SYNC', 3081, 0.01, 1951735, 975863, 0.499997694359122, 'NO SYNC', 17100, 0.01, 2896740, 1448360, 0.499996547843438, 'NO SYNC', 94912, 0.01, 1800105, 900045, 0.499995833576375, 'NO SYNC', 526805, 0.01, 2290245, 1145113, 0.499995851972169, 'NO SYNC', 2924018, 0.01, 2256745, 1128371, 0.499999335325879, 'NO SYNC', 16229682, 0.01, 2004625, 1002304, 0.49999575980545, 'NO SYNC', 90082412, 0.01, 1912945, 956468, 0.499997647606178, 'NO SYNC', 500000000, 0.01, 1421040, 710518, 0.499998592580082, 'NO SYNC'

3 个答案:

答案 0 :(得分:1)

假定CSV中的列数恒定(通常是这种情况)。并且使用块断路器来自一个令人垂涎的答案here

d = (100, 0.01, 11139155, 5569534, 0.499996094856387, 'NO SYNC', 555, 0.01, 2306110, 1153050, 0.499997831846703, 'NO SYNC', 3081, 0.01, 1951735, 975863, 0.499997694359122, 'NO SYNC', 17100, 0.01, 2896740, 1448360, 0.499996547843438, 'NO SYNC', 94912, 0.01, 1800105, 900045, 0.499995833576375, 'NO SYNC', 526805, 0.01, 2290245, 1145113, 0.499995851972169, 'NO SYNC', 2924018, 0.01, 2256745, 1128371, 0.499999335325879, 'NO SYNC', 16229682, 0.01, 2004625, 1002304, 0.49999575980545, 'NO SYNC', 90082412, 0.01, 1912945, 956468, 0.499997647606178, 'NO SYNC', 500000000, 0.01, 1421040, 710518, 0.499998592580082, 'NO SYNC')

# 6 columns in a row
chunks = [d[i:i + 6] for i in range(0, len(d), 6)]

with open ('File path', 'w') as f:
     writer = csv.writer(f, delimiter = ',')
     writer.writerows(d)

答案 1 :(得分:0)

这是一个简单的示例,说明您可能会采用这种方法。

openDialog: function() {
  if (!this.draggableDialog) {
    this.draggableDialog = new Dialog({
      title: "Charts",
      type: "Message",
      contentWidth: "900px",
      contentHeight: "700px",
      resizable: true,
      content: [
        new RadialMicroChart({
          percentage: 75,
          total: 100,
          size: "Responsive",
          valueColor: "Critical"
        })
      ],

      beginButton: new Button({
        text: "Close",
        press: function() {
          this.draggableDialog.close();
        }.bind(this)
      })
    });
    this.getView().addDependent(this.draggableDialog);
  }
  this.draggableDialog.open();

}

请注意,这里有一些不安全的假设。例如,我假设您的行长度一开始就知道。

如果您的行的长度不一致,并且想要中断特定的令牌,则可以按照以下方法进行操作:

>>> data = "1 2 3 4 5 6 7 8 9 10"
>>> items = data.split(" ")
>>> chunk_size = 5
>>> chunks = [items[i:i+chunk_size] for i in range(len(items)/chunk_size)]
>>> chunks
[['1', '2', '3', '4', '5'], ['2', '3', '4', '5', '6']]
>>> "\n".join([" ".join(chunk) for chunk in chunks])
'1 2 3 4 5\n2 3 4 5 6'

很显然,一旦有了数据行,就可以简单地将它们发送到文件中。

答案 2 :(得分:0)

我可能在这里对解决方案有些过分,但是下面的内容将为您提供您想要实现的输出。

如果您有另一个与此类似的问题,这会迫使您找到“ NO SYNC”以外的其他问题,那么这应该为将来提供可重用的功能。

就像@Rahul Chawla的答案一样,这将查找您的新行标识符NO SYNC,并将其更新为NOSYNC!。之所以有用,是因为它使我们能够通过每次看到NO SYNC时拆分一个字符串来创建以!结尾的条目列表。您可以根据数据中不存在的内容来自定义分隔符(delim参数,默认为!)附加到find参数中。

import csv

raw_data = (
100, 0.01, 11139155, 5569534, 0.499996094856387, 'NO SYNC', 555, 0.01, 2306110, 1153050, 0.499997831846703, 'NO SYNC',
3081, 0.01, 1951735, 975863, 0.499997694359122, 'NO SYNC', 17100, 0.01, 2896740, 1448360, 0.499996547843438, 'NO SYNC',
94912, 0.01, 1800105, 900045, 0.499995833576375, 'NO SYNC', 526805, 0.01, 2290245, 1145113, 0.499995851972169,
'NO SYNC', 2924018, 0.01, 2256745, 1128371, 0.499999335325879, 'NO SYNC', 16229682, 0.01, 2004625, 1002304,
0.49999575980545, 'NO SYNC', 90082412, 0.01, 1912945, 956468, 0.499997647606178, 'NO SYNC', 500000000, 0.01, 1421040,
710518, 0.499998592580082, 'NO SYNC')


def identify_new_rows(data, find, delim='!'):
    """convert a flat tuple/list, or string into a list of lists given something to `find`."""
    if isinstance(data, tuple):
        data = " ".join(map(str, data))
    elif isinstance(data, list):
        data = " ".join(data)
    data = [[x for x in d.split(' ') if str(x) != ''] for d in data.replace(find, str(find).replace(' ', '') + delim).split(delim) if len(d) > 0]
    return data



with open(r'~/path/to/your/file.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL, delimiter=',')
    wr.writerows(identify_new_rows(raw_data, 'NO SYNC'))

我会注意到,当尝试将其应用于其他数据集时,此方法存在缺陷,因为这假定您的数据中没有带空格的字符串(当前定界符除外,该字符串在列表推导中得到处理。) >