2012-06-28 14 views
0

我想從文本文件中讀取最後一行。每行開頭的數字,所以東西插在接下來的時間,新號碼將自動加1使用python轉換/連接整數到strying

例如遞增,這將是一個典型的文件

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轉換爲字符串的函數代碼,但我得到同樣的「不能連接」的錯誤。

+0

[在Python中使用字符串和整數生成字符串]可能的重複(http://stackoverflow.com/questions/2823211/making-a-string-out-of-a-string-and-an -python) –

+0

@HansEngel:這是相反的問題。 –

+0

唉,不理我。 :) –

回答

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

,那麼你已經到LastItemNum轉換回字符串寫入文件之前,使用:

LastItemNum=str(LastItemNum)或代替這一點,你可以使用字符串格式化。

+0

編輯 - 完美工作。謝謝! – user1104854

+0

在'writelines()'裏面使用'str(LastItemNum)',因爲'LastItemNum'是一個'int'。 –