pythonqt5pyqt5qfileqtextstream

PyQt5: cannot write cookie to file using QFile


I have a file named cookies.txt.

fd = QFile(":/cookies.txt")
available_cookies = QtNetwork.QNetworkCookieJar().allCookies()
for cookie in available_cookies:
   print(cookie.toRawForm(1))
   QTextStream(cookie.toRawForm(1), fd.open(QIODevice.WriteOnly))
fd.close()

Here is my full traceback:

QTextStream(cookie.toRawForm(1),        fd.open(QIODevice.WriteOnly))
TypeError: arguments did not match any overloaded call:
QTextStream(): too many arguments
QTextStream(QIODevice): argument 1 has unexpected type 'QByteArray'
QTextStream(QByteArray, mode: Union[QIODevice.OpenMode,    QIODevice.OpenModeFlag] = QIODevice.ReadWrite): argument 2 has unexpected type 'bool'

I am following the C++ documentation, and I am having trouble writing the corresponding python syntax.


Solution

  • Are you really trying to write to a resource path? Resources are read-only, so that is not going to work.

    To write to a non-resource path:

    fd = QFile('/tmp/cookies.txt')
    if fd.open(QIODevice.WriteOnly):
        available_cookies = QtNetwork.QNetworkCookieJar().allCookies()
        stream = QTextStream(fd)
        for cookie in available_cookies:
            data = cookie.toRawForm(QtNetwork.QNetworkCookie.Full)
            stream << data
        fd.close()