我想实时创建一个文件,并将与列对应的值实时添加到相应CSV
文件中的现有文件中。
如何添加在该程序中生成的每个CSV
文件?
我将写下我现在正在使用的代码。
import csv
for i in range(10):
SD="Save datas(Angle)"+str(i) ## 해당 각도별로 배열을 지정
SDArray1=str(SD) ## 파일을 만들어준다
f=open(SDArray1+".csv","a+t")# ## 이름을 만들어준 파일을 생성
csv_writer = csv.writer(f)
csv_writer.writerow([SD])
print("One loop has started")
f.close()#
for i in range(1,5):
cdata=[i]
f=open(SDArray1+".csv","a+t")
csv_writer =csv.writer(f)
csv_writer.writerow(cdata)
print(cdata)
f.close()#
print("loop's finished!")
如果您看上面的代码,则会创建一个特定的文件。我完成了下一个文件,但是我想知道如何在文件中添加列。
答案 0 :(得分:1)
csv.write_row()
包含一整列的列-如果需要更多列,请将其添加到cdata=[i]
-中。 cdata=[i,i*2,i*3,i*4]
。
您应该use with open() as f:
for file manipulation,它可以更有效地防止错误,并在离开with
块时自动关闭文件。
已修复:
import csv
# do not use i here and down below, thats confusing, better names are a plus
for fileCount in range(10):
filename = "filename{}.csv".format(fileCount) # creates filename0.csv ... filename9.csv
with open(filename,"w") as f:# # create file new
csv_writer = csv.writer(f)
# write headers
csv_writer.writerow(["data1","data2","data3"])
# write 4 rows of data
for i in range(1,5):
cdata=[(fileCount*100000+i*1000+k) for k in range(3)] # create 3 datapoints
# write one row of data [1000,1001,1002] up to [9004000,9004001,9004002]
# for last i and fileCount
csv_writer.writerow(cdata)
# no file.close- leaving wiht open() scope autocloses
检查我们写的内容:
import os
for d in sorted(os.listdir("./")):
if d.endswith("csv"):
print(d,":")
print("*"*(len(d)+2))
with open(d,"r") as f:
print(f.read())
print("")
输出:
filename0.csv :
***************
data1,data2,data3
1000,1001,1002
2000,2001,2002
3000,3001,3002
4000,4001,4002
filename1.csv :
***************
data1,data2,data3
101000,101001,101002
102000,102001,102002
103000,103001,103002
104000,104001,104002
filename2.csv :
***************
data1,data2,data3
201000,201001,201002
[...snip the rest - you get the idea ...]
filename9.csv :
***************
data1,data2,data3
901000,901001,901002
902000,902001,902002
903000,903001,903002
904000,904001,904002
要在现有文件中添加新列:
示例:
将列值的总和添加到文件中并作为新文件写入:
filename = "filename0.csv"
newfile = "filename0new.csv"
# open one file to read, open other (new one) to write
with open(filename,"r") as r, open(newfile,"w") as w:
reader = csv.reader(r)
writer = csv.writer(w)
newHeader = next(reader) # read the header
newHeader.append("Sum") # append new column-header
writer.writerow(newHeader) # write header
# for each row:
for row in reader:
row.append(sum(map(int,row))) # read it, sum the converted int values
writer.writerow(row) # write it
# output the newly created file:
with open(newfile,"r") as n:
print(n.read())
输出:
data1,data2,data3,Sum
1000,1001,1002,3003
2000,2001,2002,6003
3000,3001,3002,9003
4000,4001,4002,12003