方法一:
import csv
d = list(range(38685))
with open('./hh.csv') as f1:
f_csv = csv.DictReader(f1)
for i, row in enumerate(f_csv):
#print(row)
key1 = hello'
value1 = 'test'
row[key1] = value1
key2 = 'hahaha'
value2 = '0'
row[key2] = value2
d[i] = row
f1.close()
方法二:
headers = ['hello', 'youtube_id', 'time_start', 'time_end', 'split', 'hahaha']
with open('./hh.csv', 'w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(d)
f.close()
with open('./hh.csv','rt') as fin:
lines=''
for line in fin:
if line!='\n':
lines+=line
with open('./hh.csv','wt')as fout:
fout.write(lines)
在上面的所有中,我们分别使用了两种不同的方式来对csv文件进行行列的增加,第一种方法,首先先用一个excel表打开一个csv文件,对它进行手动添加了hello和hahaha。第二种方法,是直接利用python里面的csv模块进行改写 *** 作,在对csv文件进行 *** 作的时候,会增添许多的空行,在倒数第7行的代码开始,就是对csv文件中多出来的空格进行处理。
# -*- coding: utf8 -*-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]])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)