import csv
l = [['1', 'Wonderful Spam'],['2', 'Lovely Spam']]
#模拟数据写入一个csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)for row in l:
spamwriter.writerow(row)
#从文件读取
l=[]
with open('eggs.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')for row in spamreader:
l = l + [row]
#把两列拼接增加为第三列写回到文件
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)for row in l:
print(row)
spamwriter.writerow(row + [row[0]+row[1]])
这是一个把最后一列重复一次的例子:
import csv
with open('test.csv') as csvfile: rows = csv.reader(csvfile) with open('test1.csv','w', newline='') as f: writer = csv.writer(f) for row in rows: row.append(row[len(row)-1]) writer.writerow(row)Python是纯粹的自由软件, 源代码和解释器CPython遵循 GPL(GNU General Public License)协议[2] 。Python语法简洁清晰,特色之一是强制用空白符(white space)作为语句缩进。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)