我如何在考虑列的情况下将文本文件写入python中的csv

时间:2014-05-09 23:29:13

标签: python python-2.7 csv numpy scipy

我想将此文本文件写入CSV,同时考虑文本中的制表符分隔列。我希望列是State,Jan,Feb,Mar等(数字是平均温度)

文本文件遵循以下格式

State           Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct    Nov    Dec Average
Alabama           44.29  48.04  55.47  61.99  69.89  76.75  79.87  79.04  73.88  63.08  54.10  46.85   62.77
Arizona           42.27  46.24  51.03  57.63  66.01  75.51  80.19  78.50  72.52  61.61  49.64  42.51   60.31
Arkansas          38.48  43.76  51.96  60.36  68.62  76.40  80.57  79.26  72.26  61.47  50.32  41.59   60.42
California        45.14  48.51  51.76  56.50  63.11  70.18  75.32  74.62  69.97  61.56  51.17  44.98   59.40
Colorado          23.71  28.34  35.57  43.06  52.50  62.15  67.60  65.75  57.72  46.64  33.51  25.20   45.15
Connecticut       25.96  28.43  36.94  47.07  57.77  66.29  71.52  69.77  61.68  50.60  41.43  31.13   49.05
Delaware          33.95  35.93  44.04  53.02  62.80  71.59  76.45  74.70  68.08  56.95  47.33  38.44   55.27
Florida           58.09  59.99  64.90  69.29  75.36  79.98  81.60  81.44  79.42  72.66  66.01  59.99   70.73

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该这样做:

with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    writer = csv.writer(outfile)
    for row in csv.reader(infile):
        writer.write(row)