我正在尝试将从文本文件中读取的数据(随着循环迭代而更新的单个数字)连接到文件名中。每次都制作文件副本并迭代副本号。读取文件的原因是我希望能够从我离开的地方继续,但我一直遇到这个错误:
TypeError:只能将str(不是“int”)连接到str
我已经尝试将 str() 运算符移动到几个不同的区域,但似乎找不到让 Python 之神高兴的最佳位置......代码如下,我们正在查看底部的 copy_loop 函数,但为了完整性我有包括所有这些:
from shutil import copyfile
import time
import tkinter as tk
import threading
class App():
def __init__(self, master):
self.isrunning = False
self.button1 = tk.Button(main, text='start')
self.button1.bind ("<Button-1>", self.startrunning)
self.button1.pack()
self.button2 = tk.Button(main, text='stop')
self.button2.bind ("<Button-1>", self.stoprunning)
self.button2.pack()
def startrunning(self, event=None):
self.isrunning = True
t = threading.Thread(target=self.copy_loop)
t.start()
def stoprunning(self, event=None):
self.isrunning = False
def copy_loop(self):
read_file = open("loop_counter.txt", "r")
iteration = read_file.read()
i = iteration # why can't I make you a string???????!!!!!!!!!!!
while self.isrunning:
copyfile("TestFile.docx", "TestFile(" + str(i+1) + ").docx")
print("File has been duplicated " + str(i+1) + " times.")
i += 1
time.sleep(restTime)
iteration = open("loop_counter.txt", "w")
iteration.write(str(i))
restTime = int(5)
main = tk.Tk()
app = App(main)
main.mainloop()
感谢您提供的任何帮助。
编辑:关闭文件:
With iteration:
iteration.write(str(i))
iteration.close()