首页 > 解决方案 > 生成文本文件的多个问题

问题描述

我正在使用 Pyqt 制作我的第一个界面,使用“设计器”和 Python 对其进行配置。def clickconector该函数返回表单填写并def radio_value在作业待处理或完成时返回(“pendiente”或“terminado”)。clickconectorradio_value* 函数编写正确,但函数有问题def text_file

问题#1:由于某种原因,生成的文件与标题具有相同的内部,如果radio_value函数会出现,因为它在算法中指定它是另一个函数clickconector

问题#2:标题没有按我的意愿写。我明白了:('Terminado', 'MT16'). txt,(它写.txt在标题中)。什么时候应该:Terminado MT16。另外,文件类型在我看来不是.txt,我必须选择用鼠标像这样打开它

def clickconector (self):
    relleno = [self.bitacora.text(), self.turno.text(), self.asesor.text(), self.item.text(), self.modelo.text(), self.identificacion.text(), self.rig.text(),self.horometro.text(),self.condicion.text(),self.orden.text(), self.observacion.text()]
    form_label = ["bitacora", 'turno', 'asesor', 'item', 'modelo', 'identificacion', 'rig', 'horometro', 'condicion', 'orden', 'observacion']
    for a,b in zip (form_label, relleno):
        return (a,b)
        
def radio_value (self):
    if self.pendiente.isChecked():     
        return 'Pendiente' , self.bitacora.text()
    
    if self.terminado.isChecked():
        return'Terminado', self.bitacora.text()

def text_file (self):
    Bloc_title= self.radio_value()
    f = open(str(Bloc_title)+'. txt', 'w')
    f.write(str(self.clickconector()))   
    return f       

标签: pythontext-files

解决方案


的返回类型radio_value是 a tuple。您正在将元组转换为字符串,因此它将以 a 的形式打印tuple,即,"(value_a, value_b, value_c)"而不是value_a value_b value_c。您可以使用join空格连接元组的每个值,如下所示:

" ".join(self.radio_value())

您还写了". txt"而不是".txt"f = open(str(Bloc_title)+'. txt', 'w'). 这就是为什么. txt在文件名中。考虑到所有这些,您的text_file函数应该如下所示:

def text_file(self):
    filename = f"{' '.join(self.radio_value())}.txt"
    with open(filename, "w") as f:
        f.write(" ".join(self.clickconnector()))
        return f

请注意使用 ofwith/open而不是 just open。强烈建议使用with/open,以提高可读性和整体易用性。


推荐阅读