我在这里搜索了这个错误,但还没有看到任何与我的情况相匹配的东西(声明,我仍然习惯于Python
)。Python - 'str'对象没有属性'append'
import os
os.chdir("C:\Projects\Rio_Grande\SFR_Checking") # set working directory
stressPeriod = 1
segCounter = 1
inFlow = 0
outFlow = 0
with open(r"C:\Projects\streamflow.dat") as inputFile:
inputList = list(inputFile)
while stressPeriod <= 1:
segCounter = 1
lineCounter = 1
outputFile = open("stats.txt", 'w') # Create the output file
for lineItem in inputList:
if (((stressPeriod - 1) * 11328) + 8) < lineCounter <= (stressPeriod * 11328):
lineItem = lineItem.split()
if int(lineItem[3]) == int(segCounter) and int(lineItem[4]) == int(1):
inFlow = lineItem[5]
outFlow = lineItem[7]
lineItemMem = lineItem
elif int(lineItem[3]) == int(segCounter) and int(lineItem[4]) <> int(1):
outFlow = lineItem[7]
else:
gainLoss = str(float(outFlow) - float(inFlow))
lineItemMem.append(gainLoss)
lineItemMem = ','.join(lineItemMem)
outputFile.write(lineItemMem + "\n") # write # lines to file
segCounter += 1
inFlow = lineItem[5]
outFlow = lineItem[7]
lineCounter += 1
outputFile.close()
所以基本上这个程序应该读.dat文件,并从中解析出的信息bits
。我将文件的每一行分成一个列表,在其上执行一些math
(数学运算在文件的不同行之间,这增加了代码的复杂性)。然后,我将一个新的数字追加到列表的末尾,这是事情莫名其妙的地方。我得到以下错误:
Traceback (most recent call last):
File "C:/Users/Chuck/Desktop/Python/SFR/SFRParser2.py", line 49, in <module>
lineItemMem.append(gainLoss)
AttributeError: 'str' object has no attribute 'append'
当我给它一个打印命令测试lineItemMem
实际上是一个列表,而不是一个字符串,它打印的清单给我。如果我在代码
lineItemMem.split(",")
打破字符串,我得到一个错误说,list
对象没有属性split
。所以基本上,当我尝试执行list
操作时,该错误说明其为string
,当我尝试执行字符串操作时,错误表示它是一个列表。我已经尝试了一点点,但坦率地说不清楚问题在这里。感谢您的任何见解。
字符串是不可变的。 –
'type(lineItemMem)'是什么? – ppperry