0

我有一个包含多列的 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])
4

1 回答 1

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,但您可以简单地更改它们。

于 2013-09-24T14:07:36.223 回答