from PyQt5.QtCore import QFile # Create a QFile object file = QFile('myfile.txt') # Open the file in read-only mode if file.open(QFile.ReadOnly | QFile.Text): # Read the contents of the file text = file.readAll() # Convert the contents to a string string = str(text, encoding='utf-8') # Print the string print(string) # Close the file file.close() else: # Print an error message if the file cannot be opened print(file.errorString())
from PyQt5.QtCore import QFile # Create a QFile object file = QFile('myfile.txt') # Open the file in write-only mode if file.open(QFile.WriteOnly | QFile.Text): # Write some text to the file file.write(b'Hello, world!') # Close the file file.close() else: # Print an error message if the file cannot be opened print(file.errorString())In this example, we import the QFile module from the PyQt5.QtCore library. We create a QFile object representing the file we want to write to. We then open the file in write-only mode using the open() method and the QFile.WriteOnly flag. We write some text to the file using the write() method and close the file. If the file cannot be opened, we print an error message using the errorString() method.