在python2版本中,
打开csv文件时要用binary模式打开,即带b的方式,如wb,ab等,而不能用文本模式,如w,w+,a+等。否则,使用witerrow写,会产生空行。
但在python3版本中,直接使用wb写入式打开文件,也会出错,如下:
filename3="6-cos-result.csv"
out = open(filename3,'wb+')
csv_write = csv.writer(out,dialect='excel')
data_num=100#
for n in range(0,100):
print ("第",str(n+1),"个目标用户")
m=11
for k in range(m):
if index1[k][n]!=n:
temp=[]
num=int(index1[k][n])
temp.append(num+1)
temp.append(data1[k][n])
csv_write.writerow(temp)
out.close()
出现错误:
Traceback (most recent call last):
此时,把out = open(filename3,‘wb+’)改为out = open(filename3,‘w+’),
此时程序正常运行,但是,写入的表格中出现空行,如下:
此时,需要利用,with open(filename3,‘w’,newline=’’) as f:语句,则能够实现消除空行的问题:
filename3="6-cos-result.csv"
with open(filename3,'w',newline='') as f:
csv_write=csv.writer(f,dialect='excel')
data_num=100#
for n in range(0,100):
print ("第",str(n+1),"个目标用户")
m=11
for k in range(m):
if index1[k][n]!=n:
temp=[]
num=int(index1[k][n])
temp.append(num+1)
temp.append(data1[k][n])
csv_write.writerow(temp)
f.close()
此时,由于缩进问题,出现错误:
filename3="6-cos-result.csv"
with open(filename3,'w',newline='') as f:
csv_write=csv.writer(f,dialect='excel')
data_num=100#
for n in range(0,100):
print ("第",str(n+1),"个目标用户")
m=11
for k in range(m):
if index1[k][n]!=n:
temp=[]
num=int(index1[k][n])
temp.append(num+1)
temp.append(data1[k][n])
csv_write.writerow(temp)
f.close()
错误解决,程序正常执行