替换所有非标题行中特定列的值

时间:2016-10-22 06:06:45

标签: python csv

下面是一些在类似于(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中的所有值或单元格[row] [2](基于单元格) [行] [山口])。但是我想忽略标题行。在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)

5 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

答案 2 :(得分:0)

csv reader会生成数组,因此您可以在r[1:]

上运行它

答案 3 :(得分:0)

for(i = 1; i < 100 ; i++){ console.log("Number " + i + " with the color red") } 是行数。从1迭代使其跳过标题行。 len(cells)也应为lines

cells

答案 4 :(得分: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()