0

I'm trying to read the last line from a text file. Each line starts with a number, so the next time something is inserted, the new number will be incremented by 1.

For example, this would be a typical file

1. Something here          date
2. Something else here     date
#next entry would be  "3.   something    date"

If the file is blank I can enter an entry with no problem. However, when there are already entries I get the following error

LastItemNum = lineList[-1][0:1] +1 #finds the last item's number
TypeError: cannon concatenate 'str' and 'int objects

Here's my code for the function

 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()

I tried to convert LastItemNum to a string but I get the same "cannot concatenate" error.

user1104854
  • 2,137
  • 12
  • 51
  • 74

1 Answers1

5
LastItemNum = int(lineList[-1][0:1]) +1

then you've to convert LastItemNum back to string before writing to file, using :

LastItemNum=str(LastItemNum) or instead of this you can use string formatting.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504