python - 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'
解决方案
这是因为您没有实例化对象。你的电话是CSVFile.appendrow("", "test", 2, 3, 4, 5)
。本质上,这意味着您的 self 参数appendrow
传递的是一个空字符串参数""
。
尝试一些类似的东西CSVFile("test").appendrow("test", 2, 3, 4, 5)
您的代码中的调用也有错误self.f.write
,但我会让您修复它。
推荐阅读
- javascript - 在选择时将下拉值从函数传递给 React.useEffect()
- javascript - 重试加载 iframe 直到成功?
- javascript - 有没有办法让 v-on:click 仅显示特定对象的模式?
- r - 尝试在 r 上下载 Github 包时出错
- java - Android 蓝牙 LE 扫描仪仅在某些设备中打开手机位置时进行扫描
- css - 关闭转换,具有 !important 值,在响应时关闭
- postgresql - 在 POSTGRESQL 11.7 上 DROP TABLE 时自动 DROP FUNCTION
- office365connectors - 是否可以构建私有 Microsoft Teams 连接器
- sql-server - 创建数据库表依赖于 XML
- html - 从右到左停止动画