为什么我只收到最后一个写给fi的条目

2024-09-28 01:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将文件写入磁盘,但在写入之前,我将QListWidget中的所有项收集到文本变量中,每行用“\n”分隔,但不是获取所有行,而是仅获取最后一行:

def makeBatFile(self):
    text=""
    for each in xrange(self.listWidget.count()):
        text="echo [Task Id:%s]\n" % each
        text=text+ self.listWidget.item(each).text() +"\n"
        print text
    self.writeBatFile("batch",text)

虽然for循环中的print打印所有行,但我无法从for循环中调用writeBatfile方法,因为当我希望将所有列表项写入一个文件时,它将尝试写入文件列表中的项数。。。你知道吗

def writeBatFile(self,do="single",task=None):
    self.task=task
    now = datetime.datetime.now()

    buildCrntTime=str(now.hour) +"_" + str(now.minute)
    selected=str(self.scnFilePath.text())
    quikBatNam=os.path.basename(selected).split(".")[0]+"_"+buildCrntTime+".bat"
    if do !="batch":
        self.batfiletoSave=os.path.join(os.path.split(selected)[0],quikBatNam)
        self.task = str(self.makeBatTask())
    else:
        self.batfiletoSave=os.path.join(self.batsDir,buildCrntTime+".bat")
    try:
        writeBat=open(self.batfiletoSave,'w')
        writeBat.write(self.task)
        self.execRender()
    except: pass
    finally: writeBat.close()

在构建要传递给writeBatFile方法的内容时,我做错了什么?你知道吗


Tags: 文件pathtextselffortaskosnow
3条回答

有一个错误:在你做的每一个循环中

text="echo [Task Id:%s]\n" % each

它转储上一次迭代中的text内容。相反,你应该这样做

text += "echo [Task Id:%s]\n" % each

您正在用text=重新定义text的每次迭代都不再引用上一次循环迭代的值,因此只有循环的最后一次迭代中的text的值被传递给writeBatFile

一种解决方案是在makeBatFile中创建一个列表,并在每次迭代中向其附加text变量。然后可以将其传递到writeBatFile并通过传递给.writelines将其写入文件

您正在for循环的每个循环中写入文本变量。应将每一行附加到文本变量:

def makeBatFile(self):
    text=""
    for each in xrange(self.listWidget.count()):
        text += "echo [Task Id:%s]\n" % each
        text += self.listWidget.item(each).text() +"\n"
        print text
    self.writeBatFile("batch",text)

+=运算符是以下对象的快捷方式:

text = text + othertext

这样,您就可以在循环的每次迭代中将字符串附加到文本变量,而不是将变量重新指定给新字符串。你知道吗

相关问题 更多 >

    热门问题