我正在尝试从文本文件中读取最后一行。每一行都以一个数字开头,因此下次插入某些内容时,新数字将增加 1。
例如,这将是一个典型的文件
1. Something here date
2. Something else here date
#next entry would be "3. something date"
如果文件为空白,我可以毫无问题地输入条目。但是,当已经有条目时,我收到以下错误
LastItemNum = lineList[-1][0:1] +1 #finds the last item's number
TypeError: cannon concatenate 'str' and 'int objects
这是我的函数代码
def AddToDo(self):
FILE = open(ToDo.filename,"a+") #open file for appending and reading
FileLines = FILE.readlines() #read the lines in the file
if os.path.getsize("EnteredInfo.dat") == 0: #if there is nothing, set the number to 1
LastItemNum = "1"
else:
LastItemNum = FileLines[-1][0:1] + 1 #finds the last items number
FILE.writelines(LastItemNum + ". " + self.Info + " " + str(datetime.datetime.now()) + '\n')
FILE.close()
我试图将 LastItemNum 转换为字符串,但我得到相同的“无法连接”错误。