2016-11-10 24 views
0

我有以下形式的.csv:從CSV表樣文件

SYSID,DATA,PERIOD_NAME,ORA,MIPS 
PROD,2016-11-02,PRIME,10,3459.48 
PROD,2016-11-02,PRIME,11,2837.16 
PROD,2016-11-02,PRIME,12,2624.15 

,我想獲得輸出像這樣

SYSID DATA   PERIOD_NAME ORA MIPS 
PROD  2016-11-02 PRIME  10  3459.48 
PROD  2016-11-02 PRIME  11  2837.16 
PROD  2016-11-02 PRIME  12  2624.15 

我已經試過

import csv 
inf = open('pathtofile\\out.csv') 
reader=csv.reader(inf) 
ofile = open('pathtofile\\fuffa.txt', "wb") 
writer = csv.writer(ofile, delimiter='\t') 
for row in reader: 
    writer.writerow(row) 

但給我以下「未格式化表」

SYSID DATA PERIOD_NAME ORA MIPS 
PROD 2016-11-02 PRIME 10 3459.48 
PROD 2016-11-02 PRIME 11 2837.16 
PROD 2016-11-02 PRIME 12 2624.15 

我環顧四周,但找不到對我的問題有用的東西。 任何提示都非常感謝。

+0

這是否http://stackoverflow.com/a/33243260/2451259回答你的問題:


爲了做到這在Python 2.6的工作,該腳本可以作如下修改? – maahl

+0

謝謝@maahl,或許它有效,但我認爲Martin的答案更易於理解。 –

回答

4

你可以滾你自己的列格式如下:

import csv 

def write_cols(data): 
    col_spacer = " "  # added between columns 
    widths = [0] * len(data[0]) 

    for row in data: 
     widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)] 

    return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 


with open('input.csv', 'rb') as f_input, open('output.txt', 'w') as f_output: 
    rows = list(csv.reader(f_input)) 

    for row in write_cols(rows): 
     f_output.write(row + '\n') 

給你以下輸出文件:

SYSID DATA   PERIOD_NAME ORA MIPS  
PROD 2016-11-02 PRIME   10 3459.48 
PROD 2016-11-02 PRIME   11 2837.16 
PROD 2016-11-02 PRIME   12 2624.15 

此計算最大寬度爲每列所有值,然後空格條目因此。請注意,確保CSV文件中的所有條目都包含相同的列數,例如沒有空行。

import csv 

def write_cols(data): 
    col_spacer = " "  # added between columns 
    widths = [0] * len(data[0]) 

    for row in data: 
     widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)] 

    return [col_spacer.join("{0:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 


with open('input.csv', 'rb') as f_input: 
    with open('output.txt', 'w') as f_output: 
     rows = list(csv.reader(f_input)) 

     for row in write_cols(rows): 
      f_output.write(row + '\n') 
+0

嗨馬丁,這段代碼完全適用於Python 2.7,但不適用於2.6。 我想調整代碼以便運行在2.6以及以下提示http://stackoverflow.com/questions/40589550/indexerror-list-index-out-of-range-reading-writing-from-to文件和這裏http://stackoverflow.com/questions/40587244/why-does-a-python-script-work-on-windows-and-not-in-linux但沒有成功。你能幫我解決這個問題嗎? –

+0

它需要一些調整才能在2.6中工作。我已經添加了一個我已經在Python 2.6.6中測試過的版本。 –

+0

uhm仍然沒有工作: 對於索引,文件「format.py」,第19行,在write_cols中 return [col_spacer.join(「{0:<{width}}」 )for row in data] 文件「format.py」,第19行,在 return [col_spacer.join(「{0:<{width}}」....)for index,col in e numerate(row ))for row in data] IndexError:列表索引超出範圍 –