TypeError:预期的str,字节或os.PathLike对象,而不是元组

时间:2018-07-26 08:49:02

标签: python python-3.x pyqt

所以我试图用GUI创建一种加密程序。这是代码:

import sys
from PyQt4 import QtGui, QtCore
import os
from Crypto.Hash import SHA256
from Crypto import Random
from Crypto.Cipher import AES

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("Encryptionprogram")
        self.setWindowIcon(QtGui.QIcon('pythonicon.png'))

        self.container = QtGui.QWidget()
        self.setCentralWidget(self.container)
        self.container_lay = QtGui.QVBoxLayout()
        self.container.setLayout(self.container_lay)



        extractAction = QtGui.QAction("Leave", self)
        extractAction.setShortcut("Ctrl+Q")
        extractAction.setStatusTip("Leave the app")
        extractAction.triggered.connect(self.close_application)

        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(extractAction)

        #Inputs
        self.Input = QtGui.QLineEdit("Filname", self)

        self.Input.setFixedWidth(200)
        self.Input.setFixedHeight(25)
        self.Input.move(20, 200)
        self.Input.setSizePolicy(QtGui.QSizePolicy.Fixed,
                                 QtGui.QSizePolicy.Fixed)

        self.Input2 = QtGui.QLineEdit("password", self)

        self.Input2.setFixedWidth(200)
        self.Input2.setFixedHeight(25)
        self.Input2.move(220, 200)
        self.Input2.setSizePolicy(QtGui.QSizePolicy.Fixed,
                                  QtGui.QSizePolicy.Fixed)

        self.home()

    def home(self):

        #Enter

        self.enter_btn = QtGui.QPushButton("Enter")
        self.container_lay.addWidget(self.enter_btn)
        self.enter_btn.clicked.connect(self.run1)

        self.checkBox = QtGui.QCheckBox('Krypter?', self)
        self.checkBox.move(0, 60)

        self.checkBox2 = QtGui.QCheckBox('Decrypt', self)
        self.checkBox2.move(100, 60)

        extractAction = QtGui.QAction(QtGui.QIcon('CloseIcon.png'), 'Close Program', self)
        extractAction.triggered.connect(self.close_application)

        self.toolBar = self.addToolBar("Extraction")
        self.toolBar.addAction(extractAction)



        self.show()


    def enlarge_window(self, state):
        if state == QtCore.Qt.Checked:
            self.setGeometry(50, 50, 1250, 600)
        else:
            self.setGeometry(50, 50, 500, 300)

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, 'Attention!',
                                           "Close Program?",
                                           QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            print("Closing...")
            sys.exit()
        else:
            pass


    def closeEvent(self, event):
        event.ignore()
        self.close_application()

    def getKey(self, password):
        hasher = SHA256.new(password.encode('utf-8'))
        return hasher.digest()

    def run1(self):
        if self.checkBox.isChecked():
            Inputfilename = self.Input.text()
            Inputpassword = self.Input2.text()
            filename = str(Inputfilename)
            password = str(Inputpassword)
            print(filename, password)
            self.encrypt(self.getKey(password), filename)
            print("Done.")
        else:
            print("no work")


    def encrypt(self, key, filename):
        chunksize = 64 * 1024
        outputFile = "(Krypteret)", filename
        filesize = str(os.path.getsize(filename)).zfill(16)
        IV = Random.new().read(16)

        encryptor = AES.new(key, AES.MODE_CBC, IV)

        with open(filename, 'rb') as infile:
            with open(outputFile, 'wb') as outfile:
                outfile.write(filesize.encode('utf-8'))
                outfile.write(IV)

                while True:
                    chunk = infile.read(chunksize)

                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += b' ' * (16 - (len(chunk) % 16))

                    outfile.write(encryptor.encrypt(chunk))


    def decrypt(self, key, filename):
        chunksize = 64 * 1024
        outputFile = filename[11:]

        with open(filename, 'rb') as infile:
            filesize = int(infile.read(16))
            IV = infile.read(16)

            decryptor = AES.new(key, AES.MODE_CBC, IV)

            with open(outputFile, 'wb') as outfile:
                while True:
                    chunk = infile.read(chunksize)

                    if len(chunk) == 0:
                        break

                    outfile.write(decryptor.decrypt(chunk))
                outfile.truncate(filesize)





def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()

但是我遇到了这个错误

    Traceback (most recent call last):
  File "D:/Dokumenter - HDD/Python/GUI.py", line 119, in run1
    self.encrypt(self.getKey(password), filename)
  File "D:/Dokumenter - HDD/Python/GUI.py", line 134, in encrypt
    with open(outputFile, 'wb') as outfile:
TypeError: expected str, bytes or os.PathLike object, not tuple
Closing...

Process finished with exit code 0

我不知道该如何解决这个问题,我不仅试图在互联网上找到解决方案,而且还试图解决它,只是在出现任何潜在错误之后一直在闲逛,但此刻我什么也没发现。如果有人可以解释错误和/或提供解决方案,那对我来说将是世界。 谢谢!

2 个答案:

答案 0 :(得分:4)

您可以如下定义输出文件:

outputFile = "(Krypteret)", filename

这是一个元组,因此是错误。目前尚不清楚您的意思。也许您想在现有文件名前加上“(Krypteret)”一词?在这种情况下,您应该

outputFile = "(Krypteret)" + filename

(将来,请减少代码量。错误完全在encrypt方法内,您应该刚刚发布该方法。)

答案 1 :(得分:0)

或者这个:

outputFile = "(Krypteret)%s"%filename

或者这个:

outputFile = "(Krypteret){}".format(filename)

这无法正常工作取决于您的python版本:

outputFile = f"(Krypteret){filename}"

您的代码无效,因为outputFile = "(Krypteret)", filename返回一个元组。