from PyQt5.QtCore import QFile, QIODevice filename = 'example.txt' # Open the file in write mode file = QFile(filename) if not file.open(QIODevice.WriteOnly | QIODevice.Text): print(f"Could not open file {filename} for writing.") else: # Write some text to the file text = "Hello, world!" file.write(text.encode('utf-8')) file.close()
from PyQt5.QtCore import QFile, QIODevice filename = 'example.bin' # Open the file in write mode file = QFile(filename) if not file.open(QIODevice.WriteOnly): print(f"Could not open file {filename} for writing.") else: # Write some binary data to the file data = bytearray([0, 1, 2, 3, 4, 5]) file.write(bytes(data)) file.close()In both of the above examples, we first create a QFile object and then try to open the designated file with the desired mode. If the file open operation is successful, we then use the write function to write data (either text or binary) to the file. The PyQt5 package library is a set of Python bindings for the Qt GUI toolkit. It allows developers to create cross-platform GUI applications with Python and Qt.