我正在尝试从文本文件中读取最后一行.每行以数字开头,因此下次插入某些内容时,新数字将增加1.
例如,这将是一个典型的文件
1. Something here date
2. Something else here date
#next entry would be "3. something date"
Run Code Online (Sandbox Code Playgroud)
如果文件为空,我可以输入一个没有问题的条目.但是,当已经有条目时,我收到以下错误
LastItemNum = lineList[-1][0:1] +1 #finds the last item's number
TypeError: cannon concatenate 'str' and 'int objects
Run Code Online (Sandbox Code Playgroud)
这是我的功能代码
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()
Run Code Online (Sandbox Code Playgroud)
我试图将LastItemNum转换为字符串,但我得到相同的"无法连接"错误.
LastItemNum = int(lineList[-1][0:1]) +1
Run Code Online (Sandbox Code Playgroud)
然后你要LastItemNum在写入文件之前转换回字符串,使用:
LastItemNum=str(LastItemNum) 或者代之以你可以使用字符串格式.
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |