2013-04-18 81 views
0

我在重寫CSV文件時遇到問題。我所擁有的是一個帶有20列的CSV文件,我將其重寫爲5個。現在,我需要拿出幾個不必要的點,其中SN < 20.它的工作原理是唯一的問題是它不會將行。它把一切都在第1行。我猜它從,如何分隔csv文件的行

output_ary.append(row) 

,但我不知道還有什麼寫在那裏。下面是代碼的一部分:

import csv 
import os 
import matplotlib.pyplot as plt 

os.chdir("C:\Users\Robert\Documents\qwe") 

r = csv.reader(open("gdweights_feh_robert_cmr.csv",'rU')) 

w = csv.writer(open("gdweight.csv",'wb',buffering=0)) 

zerovar2 = 0 
for row in r: 
     if zerovar2==0: 
     zerovar2 = zerovar2 + 1 
    else: 
       sn = float(row[11]) 
       rweight = float(row[17]) 
       tarweight = float(row[18]) 
       fehadop = float(row[25]) 
       weight = rweight*tarweight*fehadop 
       w.writerow([sn,rweight,tarweight,fehadop,weight]) 



output_ary = [] 

with open("gdweight.csv",'rU') as f: 
    reader = csv.reader(f, delimiter= ',') 
    zerovar = 0 
    for row in reader: 
     if zerovar==0: 
       zerovar = zerovar + 1 
     else: 
       sn = row [0] 
       zerovar = zerovar + 1 
       x = float(sn) 
       if x > 20: 
        output_ary.append(row) 

with open("ouput1.csv",'w') as f2: 
    for row in output_ary: 
     for item in row: 
      f2.write(item + ",") 
+2

爲什麼不使用'csv.writer'而不是直接寫入文件?寫一個csv文件還有更多的事情要寫在兩個字符串之間寫逗號... – jadkik94

+2

順便說一句,你的縮進看起來很奇怪。很多時候縮進不會粘貼到SO中,但您可能需要(1)使用'python -tt your_program_name.py'運行代碼以確保它不是不一致的,並且(2)切換到使用四個空格而不是標籤。 – DSM

+0

對於那些(因爲我是)想知道什麼-tt的意思,你可以在這裏找到它:http://docs.python.org/2/using/cmdline.html – Dvx

回答

1
with open("ouput1.csv",'w') as f2: 
    for row in output_ary: 
     for item in row: 
      f2.write(item + ",") 
     f2.write("\n") # this is what you're missing 
+0

這很簡單,我只是想不起來。謝謝馬特! –

0

簡單重寫了最後爲:

with open("ouput1.csv",'w') as f2: 
    for row in output_ary: 
     f2.write(",".join([str(e) for e in item] + '\n') 

現在這裏有一對夫婦的補充意見:

你可以用枚舉,而不是使用計數器:

for i_row, row in enumerate(r) : 
    ... 

您也可以使用csv編寫器:

with open("output.txt", "w") as f : 
    csv_w = csv.writer(f) 
    for i_row, row in enumerate(output) : 
     if i_row== 0 : 
      continue 
     csv_w.writerow(row)