首页 > 解决方案 > AttributeError:“str”对象没有属性“csv”

问题描述

我正在尝试编写一个 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'

标签: python

解决方案


这是因为您没有实例化对象。你的电话是CSVFile.appendrow("", "test", 2, 3, 4, 5)。本质上,这意味着您的 self 参数appendrow传递的是一个空字符串参数""

尝试一些类似的东西CSVFile("test").appendrow("test", 2, 3, 4, 5)

您的代码中的调用也有错误self.f.write,但我会让您修复它。


推荐阅读