我想從文本文件中讀取最後一行。每行開頭的數字,所以東西插在接下來的時間,新號碼將自動加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轉換爲字符串的函數代碼,但我得到同樣的「不能連接」的錯誤。
[在Python中使用字符串和整數生成字符串]可能的重複(http://stackoverflow.com/questions/2823211/making-a-string-out-of-a-string-and-an -python) –
@HansEngel:這是相反的問題。 –
唉,不理我。 :) –