-1

我正在尝试将从文本文件中读取的数据(随着循环迭代而更新的单个数字)连接到文件名中。每次都制作文件副本并迭代副本号。读取文件的原因是我希望能够从我离开的地方继续,但我一直遇到这个错误:

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

2 回答 2

2

你的问题不在于你没有做成i一个字符串。这是它已经一个字符串,甚至在你尝试之前——因此,添加1它是非法的。

首先,你read从一个文件中获取它。这总是返回一个str

iteration = read_file.read()
i = iteration # why can't I make you a string???????!!!!!!!!!!!

然后,您尝试在多个位置向该字符串添加 1,每个位置都会为您提供TypeError

copyfile("TestFile.docx", "TestFile(" + str(i+1) + ").docx")
print("File has been duplicated " + str(i+1) + " times.")
i += 1

要解决此问题,请在读取字符串后立即将其转换为 int,如下所示:

i = int(iteration)

然后,您的其余代码将起作用,因为您的其余代码都期望i是一个 int。

但是,您应该考虑通过使用字符串格式来简化它,而不是手动将内容转换为字符串并将它们连接起来。例如,这更容易阅读,也更难出错:

copyfile("TestFile.docx", f"TestFile({i+1}).docx")

或者,如果您必须使用旧版本的 Python:

copyfile("TestFile.docx", "TestFile({}).docx".format(i+1))
于 2018-09-07T17:45:05.047 回答
0

这仅仅是因为i是字符串并且1在你的情况下是整数。您需要做的就是在与1相加之前将str(int(i)+1)其转换i为整数,然后将整个整数再次转换为字符串。

于 2018-09-07T17:55:46.617 回答