写入csv时格式化列

时间:2017-03-28 10:05:22

标签: python csv

我尝试使用Python将以下列表列表写入.csv文件中的列。

writelist = [['MET            ', '===============', 'eT_miss_inv', 'eT_miss_lep', 'eT_miss_seed', 'met_avPt_seed'], ['Photon         ', '===============', 'pass1phtriggers', 'nPh', 'topoetcone40_1ph', 'ptvarcone20_1ph', 'pT_1ph', 'eta_1ph', 'phi_1ph', 'dPhi_1ph', 'dPhi_1ph1jet', 'phi_V', 'nbaselinePh', 'dphimin4_lep'], ['Weight         ', '===============', 'j1_bweight', 'j1_bweight', 'j1_bweight', 'j2_bweight', 'j2_bweight', 'j2_bweight', 'LeptonWeight', 'TriggerWeight'], ['HLT            ', '===============', 'HLT_g120_loose', 'HLT_g140_loose', 'HLT_e20_medium', 'HLT_2e17_loose', 'HLT_mu20_iloose_L1MU15', 'HLT_mu26', 'HLT_2mu6', 'HLT_mu50'], ['Truth          ', '===============', 'pT_1jet_truth'], ['Other          ', '===============', 'RG', 'nbjets_seed', 'mctcorr2b', 'E_V', 'pT_V', 'pT_1jet_seed', 'topness', 'centrality', 'btagzerolep_channel', 'allGhostGood', 'averageIntPerXingCorr', 'CoreFlag', 'btag0l_channel', 'sumet_refjet_seed', 'pT_2jet_seed', 'isTruthAnalysis', 'mctcorrjj', 'pass1Ltriggers', 'eta_V', 'pT_B']]

每个子列表的前两个元素都是装饰性的(标题+分隔)。我尝试使用标签均匀分隔列,如下所示:

import csv
from itertools import izip_longest
writelist = [['MET            ', '===============', 'eT_miss_inv', 'eT_miss_lep', 'eT_miss_seed', 'met_avPt_seed'], ['Photon         ', '===============', 'pass1phtriggers', 'nPh', 'topoetcone40_1ph', 'ptvarcone20_1ph', 'pT_1ph', 'eta_1ph', 'phi_1ph', 'dPhi_1ph', 'dPhi_1ph1jet', 'phi_V', 'nbaselinePh', 'dphimin4_lep'], ['Weight         ', '===============', 'j1_bweight', 'j1_bweight', 'j1_bweight', 'j2_bweight', 'j2_bweight', 'j2_bweight', 'LeptonWeight', 'TriggerWeight'], ['HLT            ', '===============', 'HLT_g120_loose', 'HLT_g140_loose', 'HLT_e20_medium', 'HLT_2e17_loose', 'HLT_mu20_iloose_L1MU15', 'HLT_mu26', 'HLT_2mu6', 'HLT_mu50'], ['Truth          ', '===============', 'pT_1jet_truth'], ['Other          ', '===============', 'RG', 'nbjets_seed', 'mctcorr2b', 'E_V', 'pT_V', 'pT_1jet_seed', 'topness', 'centrality', 'btagzerolep_channel', 'allGhostGood', 'averageIntPerXingCorr', 'CoreFlag', 'btag0l_channel', 'sumet_refjet_seed', 'pT_2jet_seed', 'isTruthAnalysis', 'mctcorrjj', 'pass1Ltriggers', 'eta_V', 'pT_B']]
with open("result.csv","w+") as f:
writer = csv.writer(f, delimiter = '\t')
for values in izip_longest(*writelist):
    writer.writerow(values)

但是,正如可以通过打开result.csv来检查,对齐方式并未正确显示。我该如何解决?

1 个答案:

答案 0 :(得分:0)