如何在pyqt中保存默认名称和扩展名的文件?

时间:2017-04-30 00:17:08

标签: python pyqt

我正在尝试保存文件,但我希望该文件具有默认名称,除非用户选择更改名称。不得更改文件扩展名。这是我尝试过的:

问题是它保存文件但不保存默认文件名或扩展名。

def save(self):
    filename, extension = QtGui.QFileDialog.getSaveFileNameAndFilter(
        self, 'Save File', '.', filter=self.tr("Backup file (*.bak)"))
    with open("text.txt", 'r') as te, open(filename, "w") as backup:
        for line in te:
            backup.writelines(line)

2 个答案:

答案 0 :(得分:1)

您需要连接文件名和扩展名:

backup_name = filename + extension

with open("text.txt", 'r') as te, open(backup_name, "w") as backup:
    ...

答案 1 :(得分:1)

我能够以这种方式使用默认文件名保存:

def save(self):
    filename, extension = QtGui.QFileDialog.getSaveFileNameAndFilter(
        self, 'Save file', 'backup_x', filter=self.tr(".bak"))
    try:
        with open("text.txt", 'r') as inst, open(filename + extension, "w") as backup:
            for line in inst:
                backup.writelines(line)
    except IOError:
        pass