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])
我有一個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])
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,但你可以簡單地改變了他們。
讀者不寫..檢查這篇文章作爲參考; http://stackoverflow.com/questions/14978575/writing-reading-the-same-csv-file-in-python – karthikr