2013-10-07 42 views
1

我在我的CSV清除數據的第2列下面的代碼(未遂):清除或CSV文件中刪除第2列與Python

def del_col(in_path): 
    # read file into memory 
     file_obj = open(in_path, 'rb') 
     reader = csv.reader(file_obj, delimiter='\t') 


# delete the status column here: 



# Now write csv back to same file: 

     # write data to file 
     file_obj = open(in_path, 'rb') 
     writer = csv.writer(file_obj) 
     writer.writerows(data) 
     file_obj.close() 

我不知道是否或如何清除此列。我是否應該逐行讀取數據並清除每行的第二個條目?還是有更簡單的方法來簡單地清除第二列?

這裏是第2次嘗試:

def del_col(in_path): 
    # read file into memory 
    file_obj = open(in_path, 'rb') 
    reader = csv.reader(file_obj, delimiter='\t') 
    data = [] 
    for row in reader: 

    # delete the status column here: 

     vals = [x[:1] + x[2:] for x in reader] 
     print vals 
     file_obj.close() 

    print 'Delete the 2nd Column (Lead Status?)' 
    conf = raw_input('delete these leads? (Y|N): ').upper()[0] 

    if conf == 'Y': 
     # write data to file 
     file_obj = open(in_path, 'wb') 
     writer = csv.writer(file_obj) 
     writer.writerows(data) 
     file_obj.close() 
+0

請使用下面的代碼,而不是額外的'在閱讀器循環中行。 'vals ='行是'for'循環的單行版本,它貫穿讀者的每一行,所以'for row'行會混淆視聽。我編輯我的答案,使用名稱'行'而不是'x'來避免混淆... – beroe

回答

1

,我只想讀成一個列表,但省略了第二欄:

def del_col(in_path): 
    # read file into memory 
    file_obj = open(in_path, 'rb') 
    readfile = csv.reader(file_obj, delimiter='\t') 

    # delete the status column here: 

    vals = [row[:1] + row[2:] for row in readfile] 
    print vals 
    file_obj.close() # if you are going to use the same file name, close and re-open 

    # Now write csv to new file: 
    # write data to file 
    out_path = in_path + "_out.dat" 
    out_obj = open(out_path, 'w') 
    writefile = csv.writer(out_obj, delimiter='\t') 
    writefile.writerows(vals) 
    out_obj.close() 

其他的想法:不要寫入同一個文件,你正在閱讀。 (在這種情況下,我生成了一個基於舊名稱的新名稱。)您需要使用'w'而不是'r'打開目標文件,並將分隔符添加到csv.writer() ...

+0

你可以看看我上面編輯的代碼嗎?我利用你的中間代碼部分和我在其他函數中使用過的佈局,但是無法運行它。 – gigawatts

+0

我在for循環行上收到縮進錯誤 – gigawatts

+0

對不起。你在你的編輯器中使用製表符或空格嗎?那裏可能有一些空白格式的混合。嘗試再次複製(我編輯過),或者刪除生成錯誤的行周圍的所有前導空白並重新插入它們,或者在編輯器中顯示不可見,並確保其一致。 – beroe