1.错误
在许多文件中,写入csv文件时都加"wb",w指写入,b指二进制
如:
csvwrite=csv.writer(open("output.csv","wb"))
Temp=["row1","row2","row3",]
csvwrite.writerow(Temp)
或者是
#!/usr/bin/env python #coding:utf-8 import csv #csv写数据 def writeCsv(file_name="C:\\Users\\Administrator\\Desktop\\test.csv"): with open(file_name,‘wb‘) as f: writer=csv.writer(f) writer.writerow([‘element‘,‘system‘]) data=[ (‘selenium‘,‘webdriver‘), (‘appium‘,‘android‘), (‘appium‘,‘ios‘), (‘selenium‘,‘python‘)] writer.writerows(data) f.close() if __name__==‘__main__‘: writeCsv() #print(getCsv(0,0))
运行结果都会出错:
TypeError: a bytes-like object is required, not ‘str‘
Traceback (most recent call last): File "E:\automatic\sc\data_driven_test\ddt_test.py", line 29, in <module> writeCsv() File "E:\automatic\sc\data_driven_test\ddt_test.py", line 9, in writeCsv writer.writerow([‘element‘,‘system‘]) TypeError: a bytes-like object is required, not ‘str‘ [Finished in 0.4s]
2.解决方法
写入时只添加“w”而不是“wb”
将上述代码改为:with open(file_name,‘w‘) as f:
可执行通过,但是打开csv文件会发现每一行后面都会多一行空行
只需将代码改为 with open(file_name,‘w‘,”newline=‘‘) as f:
原文地址:https://www.cnblogs.com/dhs94/p/9038820.html
时间: 2024-10-14 16:53:02