我正在将文件写入磁盘,但在写入之前,我将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方法的内容时,我做错了什么?你知道吗
有一个错误:在你做的每一个循环中
它转储上一次迭代中的
text
内容。相反,你应该这样做您正在用
text=
重新定义text
的每次迭代都不再引用上一次循环迭代的值,因此只有循环的最后一次迭代中的text
的值被传递给writeBatFile
一种解决方案是在
makeBatFile
中创建一个列表,并在每次迭代中向其附加text
变量。然后可以将其传递到writeBatFile
并通过传递给.writelines
将其写入文件您正在for循环的每个循环中写入文本变量。应将每一行附加到文本变量:
+=运算符是以下对象的快捷方式:
这样,您就可以在循环的每次迭代中将字符串附加到文本变量,而不是将变量重新指定给新字符串。你知道吗
相关问题 更多 >
编程相关推荐