尝试在Python循环中连接读取数据但收到错误

问题描述 投票:-1回答:2

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

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()
python python-3.x loops formatting concatenation
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))

0
投票

这只是因为i是字符串而1在你的情况下是整数。您需要做的就是使用str(int(i)+1)i转换为整数,然后再加1,然后再将整个整数更改为字符串。

© www.soinside.com 2019 - 2024. All rights reserved.