我正在尝试编写CSV文件,并且我具有创建带有头文件的文档的代码,该代码将使用输入内容来写入同一文件。
class CSVFile:
def __init__(self, doctitle):
#creates the physical doc on the disk
#creates the header row in the .csv file
self.doctitle = doctitle
self.f = open(doctitle + ".csv", 'w+')
self.f.write("vianumber, innerdiameter, outerdiamter, ratio \n")
self.closedoc()
return
def appendrow(self, doctitle, vianumber, innerdiameter, outerdiamter, ratio):
#called for each measured via
self.f = open(doctitle + ".csv", 'a+')
self.f.write(vianumber, innerdiameter, outerdiamter, ratio)
self.closedoc()
return
def closedoc(self):
#filize the document
self.f.close()
return
我收到的错误消息如下:
CSVFile.appendrow("", "test", 2, 3, 4, 5)
Traceback (most recent call last):
File "<ipython-input-21-07d259b7d2fa>", line 1, in <module>
CSVFile.appendrow("", "test", 2, 3, 4, 5)
File "C:/Users/Brook/Desktop/Senior Design/CSV file script.py", line 23, in appendrow
self.f = open(doctitle + ".csv", 'a+')
AttributeError: 'str' object has no attribute 'f'
答案 0 :(得分:0)
这是因为您没有实例化对象。您的电话是CSVFile.appendrow("", "test", 2, 3, 4, 5)
。
本质上,这意味着对于appendrow
的self参数,您要传递一个空字符串参数""
。
尝试一些CSVFile("test").appendrow("test", 2, 3, 4, 5)
您的代码中的self.f.write
调用中也有一个错误,但我会让您解决。
答案 1 :(得分:0)
您的课程及其使用方式有很多问题,例如:
with
块。self
参数传递给对象方法。这是您代码的改进版本。
import csv
class CSVFile:
def __init__(self, doctitle):
self.doctitle = doctitle + ".csv"
with open(doctitle, 'w+') as f:
writer = csv.writer(f)
writer.writerow(["vianumber", "innerdiameter",
"outerdiamter", "ratio"])
def appendrow(self, vianumber, innerdiameter, outerdiamter, ratio):
#called for each measured via
with open(self.doctitle, 'a+') as f:
writer = csv.writer(f)
writer.writerow([vianumber, innerdiameter, outerdiamter, ratio])
#def closedoc(self): -- Not needed!
#filize the document
mycsv = CSVFile("foo")
mycsv.appendrow(2,3,4,5)