2016-10-22 35 views
0

下面是一些運行在與此類似的文件(old_file.csv)上的python代碼。替換所有非標題行中特定列的值

A,B,C,D 
1,2,XX,3 
11,22,XX,33 
111,222,XX,333 

如何可以通過在old_file.csv所有行迭代(如果不知道該文件的長度),並在列C或索引2或細胞[行]替換所有值[2] (基於單元格[row] [col])。但我想忽略標題行。在new_file.csv中,包含'XX'的所有值都將變成'YY'。

import csv 
r = csv.reader(open('old_file.csv')) 
cells = [l for l in r] 
cells[1][2] = 'YY' 
cells[2][2] = 'YY' 
cells[3][2] = 'YY' 
w = csv.writer(open('new_file.csv', 'wb')) 
w.writerows(cells) 
+0

凡'lines'哪裏來的? – Soviut

+0

應該是「單元格」 – MacGyver

回答

1

在@Soviut ANS只是小改,試試這個我認爲這將有助於你

import csv 

rows = csv.reader(open('old_file.csv')) 
newRows=[] 
for i, row in enumerate(rows): 
    # ignore the first row, modify all the rest 
    if i > 0: 
     row[2] = 'YY'  
    newRows.append(row) 
# write rows to new CSV file, no header is written unless explicitly told to 
w = csv.writer(open('new_file.csv', 'wb')) 
w.writerows(newRows) 
0

CSV讀者使得陣列,所以你可以只在r[1:]

+0

您可以具體嗎?我從來沒有寫過Python腳本。 – MacGyver

+0

您問過如何忽略標題行。在'for'循環中,不是運行在'r'上,而是運行在'r [1:]' –

0

len(cells)運行它的行數。從1開始迭代使其跳過標題行。 lines也應該是cells

import csv 
    r = csv.reader(open('old_file.csv')) 
    cells = [l for l in r] 
    for i in range(1, len(cells)): 
     cells[i][2] = 'YY' 
    w = csv.writer(open('new_file.csv', 'wb')) 
    w.writerows(cells) 
1

您可以非常容易地遍歷行數組並替換目標單元格中​​的值。

# get rows from old CSV file 
rows = csv.reader(open('old_file.csv')) 

# iterate over each row and replace target cell 
for i, row in enumerate(rows): 
    # ignore the first row, modify all the rest 
    if i > 0: 
     row[2] = 'YY' 

# write rows to new CSV file, no header is written unless explicitly told to 
w = csv.writer(open('new_file.csv', 'wb')) 
w.writerows(rows) 
+0

請注意,這將替換標題行中的元素,這不是您想要的。其實一個簡單的解決方法就像在'for row in row [1:]'中一樣。但是你必須處理空文件,否則'IndexError'是可能的。 – table

0
read_handle = open('old_file.csv', 'r') 
data = read_handle.read().split('\n') 
read_handle.close() 
new_data = [] 
new_data.append(data[0]) 
for line in data[1:]: 
    if not line: 
     new_data.append(line) 
     continue 
    line = line.split(',') 
    line[2] = 'YY' 
    new_data.append(','.join(line)) 
write_handle = open('new_file.csv', 'w') 
write_handle.writelines('\n'.join(new_data)) 
write_handle.close() 
+0

首先,這將在空文件上發生IndexError失敗。其次,'csv'是python的內置包,所以當你使用.csv文件時,最好使用它。 – table

+0

我同意。謝謝。但是,答案只針對問題,並不一定處理所有可能出現的錯誤情況 - 例如只包含2個元素的行(所以,行[2]也會引發IndexError)。至於csv模塊,如果使用和que中描述的一樣簡單,我沒有看到使用csv模塊的任何附加好處。 – Sharad

+0

這是一個外殼一個內襯(它雖然修剪掉空行): head -1 old_file.csv && cat old_file.csv | awk -F,-v OFS =,'NF && NR> 1 {$ 3 =「YY」;打印}'| tee new_file.csv – Sharad

相關問題