file = QFile("example.txt") if file.open(QFile.ReadWrite | QFile.Text): # perform some file operations file.close()
file = QFile("example.txt") with open(file, 'w') as f: # perform some file operations file.close()In this example, a QFile object is instantiated with the filename 'example.txt'. The file is then opened for writing using the 'w' mode, and file operations are performed inside a 'with' statement. When the 'with' statement is exited, the file is automatically closed using the .close() method. Package library: PyQt5.QtCore.