为什么不插入?

时间:2013-09-24 13:44:13

标签: python csv insert

我有一个包含多列的csv文件,如果它是空白的话,我想将一列的内容添加到相邻列中。

import csv
with open("new.csv", "r+b") as f:
reader = csv.reader(f)
for rows in reader:
    if rows[4] == "":
        rows.insert(5,rows[3])

1 个答案:

答案 0 :(得分:0)

with open('i.csv', 'r') as f:
    reader = csv.reader(f)
    my_list = []
    for rows in reader:
        sub_list = []
        for item in rows:
            # Replace even values by 0
            # This can be changed to do something else
            if int(item) % 2 == 0:
                item = 0
            sub_list.append(item)
        my_list.append(sub_list)       

print my_list
# output
#[['1', 0, '3', 0],
#[0, '3', 0, '5'],
#['5', 0, '7', 0],
#['9', 0, '11', 0],
#['13', 0, '15', 0]]

# Write the modified content to the same file
with open('i.csv', 'w') as f:
    writer = csv.writer(f)
    for row in my_list:
        writer.writerow(row)




# Read it to see if it worked
with open('i.csv', 'r') as f:
    for line in f.readlines():
        print line

# output
# 1,0,3,0
# 0,3,0,5
# 5,0,7,0
# 9,0,11,0
# 13,0,15,0

我在该脚本中所做的是将所有偶数替换为0,但您可以简单地更改它们。