Skip to content

PythonQt.Qt.QFile

QFile

PythonQtInstanceWrapper object

Native bases: PythonQtInstanceWrapper

Supplemental documentation: Qt 5 reference:

Detailed Description

QFile is an I/O device for reading and writing text and binary files and resources. A QFile may be used by itself or, more conveniently, with a QTextStream or QDataStream.

The file name is usually passed in the constructor, but it can be set at any time using setFileName(). QFile expects the file separator to be '/' regardless of operating system. The use of other separators (e.g., '\') is not supported.

You can check for a file's existence using exists(), and remove a file using remove(). (More advanced file system related operations are provided by QFileInfo and QDir.)

The file is opened with open(), closed with close(), and flushed with flush(). Data is usually read and written using QDataStream or QTextStream, but you can also call the QIODevice-inherited functions read(), readLine(), readAll(), write(). QFile also inherits getChar(), putChar(), and ungetChar(), which work one character at a time.

The size of the file is returned by size(). You can get the current file position using pos(), or move to a new file position using seek(). If you've reached the end of the file, atEnd() returns true.

Reading Files Directly

The following example reads a text file line by line:

    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        process_line(line);
    }

The QIODevice::Text flag passed to open() tells Qt to convert Windows-style line terminators ("\r\n") into C++-style terminators ("\n"). By default, QFile assumes binary, i.e. it doesn't perform any conversion on the bytes stored in the file.

Using Streams to Read Files

The next example uses QTextStream to read a text file line by line:

    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        process_line(line);
    }

QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode QString. By default, it assumes that the user system's local 8-bit encoding is used (e.g., UTF-8 on most unix based operating systems; see QTextCodec::codecForLocale() for details). This can be changed using QTextStream::setCodec().

To write text, we can use operator\<\<(), which is overloaded to take a QTextStream on the left and various data types (including QString) on the right:

    QFile file("out.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << "The magic number is: " << 49 << "\n";

QDataStream is similar, in that you can use operator\<\<() to write data and operator>>() to read it back. See the class documentation for details.

When you use QFile, QFileInfo, and QDir to access the file system with Qt, you can use Unicode file names. On Unix, these file names are converted to an 8-bit encoding. If you want to use standard C++ APIs (<cstdio> or <iostream>) or platform-specific APIs to access files instead of QFile, you can use the encodeName() and decodeName() functions to convert between Unicode file names and 8-bit file names.

On Unix, there are some special system files (e.g. in /proc) for which size() will always return 0, yet you may still be able to read more data from such a file; the data is generated in direct response to you calling read(). In this case, however, you cannot use atEnd() to determine if there is more data to read (since atEnd() will return true for a file that claims to have size 0). Instead, you should either call readAll(), or call read() or readLine() repeatedly until no more data can be read. The next example uses QTextStream to read /proc/modules line by line:

    QFile file("/proc/modules");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    QString line = in.readLine();
    while (!line.isNull()) {
        process_line(line);
        line = in.readLine();
    }

Signals

Unlike other QIODevice implementations, such as QTcpSocket, QFile does not emit the aboutToClose(), bytesWritten(), or readyRead() signals. This implementation detail means that QFile is not suitable for reading and writing certain types of files, such as device files on Unix platforms.

Platform Specific Issues

File permissions are handled differently on Unix-like systems and Windows. In a non writable directory on Unix-like systems, files cannot be created. This is not always the case on Windows, where, for instance, the 'My Documents' directory usually is not writable, but it is still possible to create files in it.

Qt's understanding of file permissions is limited, which affects especially the QFile::setPermissions() function. On Windows, Qt will set only the legacy read-only flag, and that only when none of the Write* flags are passed. Qt does not manipulate access control lists (ACLs), which makes this function mostly useless for NTFS volumes. It may still be of use for USB sticks that use VFAT file systems. POSIX ACLs are not manipulated, either.

On Android, some limitations apply when dealing with content URIs:

  • Access permissions might be needed by prompting the user through the QFileDialog which implements Android's native file picker.
  • Aim to follow the Scoped storage guidelines, such as using app specific directories instead of other public external directories. For more information, also see storage best practices.
  • Due to the design of Qt APIs (e.g. QFile), it's not possible to fully integrate the latter APIs with Android's MediaStore APIs.

Source: https://doc.qt.io/archives/qt-5.15/qfile.html

Complete member index

Every captured member retains its own identity. Identical captured declaration text is linked once; this does not establish native inheritance or interchangeable objects.

Member Kind Signature Summary
AbortError attribute Any (shared captured text)
Append attribute Any (shared captured text)
AutoCloseHandle attribute Any (shared captured text)
CopyError attribute Any (shared captured text)
DontCloseHandle attribute Any (shared captured text)
ExeGroup attribute Any (shared captured text)
ExeOther attribute Any (shared captured text)
ExeOwner attribute Any (shared captured text)
ExeUser attribute Any (shared captured text)
FatalError attribute Any (shared captured text)
FileError attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
FileHandleFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
FileHandleFlags attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
MapPrivateOption attribute Any (shared captured text)
MemoryMapFlags attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
NoError attribute Any (shared captured text)
NoOptions attribute Any (shared captured text)
NotOpen attribute Any (shared captured text)
OpenError attribute Any (shared captured text)
OpenMode attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
OpenModeFlag attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
Permission attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
Permissions attribute type Convert a number or string to an integer, or return 0 if no arguments are given. (shared captured text)
PermissionsError attribute Any (shared captured text)
PositionError attribute Any (shared captured text)
ReadError attribute Any (shared captured text)
ReadGroup attribute Any (shared captured text)
ReadOnly attribute Any (shared captured text)
ReadOther attribute Any (shared captured text)
ReadOwner attribute Any (shared captured text)
ReadUser attribute Any (shared captured text)
ReadWrite attribute Any (shared captured text)
RemoveError attribute Any (shared captured text)
RenameError attribute Any (shared captured text)
ResizeError attribute Any (shared captured text)
ResourceError attribute Any (shared captured text)
Text attribute Any (shared captured text)
TimeOutError attribute Any (shared captured text)
Truncate attribute Any (shared captured text)
Unbuffered attribute Any (shared captured text)
UnspecifiedError attribute Any (shared captured text)
WriteError attribute Any (shared captured text)
WriteGroup attribute Any (shared captured text)
WriteOnly attribute Any (shared captured text)
WriteOther attribute Any (shared captured text)
WriteOwner attribute Any (shared captured text)
WriteUser attribute Any (shared captured text)
__init__ function (self, *args: Any, **kwargs: Any) -> None Native constructor; consult class documentation for supported overloads. (shared captured text)
aboutToClose function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.aboutToClose; argument details are not documented.
atEnd function (self) -> bool X.atEnd() -> bool (shared captured text)
blockSignals function (self, b: Any) -> bool X.blockSignals(b) -> bool (shared captured text)
bytesAvailable function (self) -> int X.bytesAvailable() -> int (shared captured text)
bytesToWrite function (self) -> int X.bytesToWrite() -> int (shared captured text)
bytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.bytesWritten; argument details are not documented.
canReadLine function (self) -> bool X.canReadLine() -> bool (shared captured text)
channelBytesWritten function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.channelBytesWritten; argument details are not documented.
channelReadyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.channelReadyRead; argument details are not documented.
childEvent function (self, event: Any) -> Any (shared captured text)
children function (self) -> tuple X.children() -> tuple (shared captured text)
className function (self, *args: Any, **kwargs: Any) -> Any Return the classname of the object (shared captured text)
close function (self) -> Any (shared captured text)
connect function (self, signal: Any, receiver: Any, slot: Any, type: Any) -> bool X.connect(signal, receiver, slot, type) -> bool (shared captured text)
copy function (self, fileName: Any, newName: str) -> bool X.copy(fileName, newName) -> bool (shared captured text)
customEvent function (self, event: Any) -> Any (shared captured text)
decodeName function (self, localFileName: Any) -> str X.decodeName(localFileName) -> str (shared captured text)
delete function (self, *args: Any, **kwargs: Any) -> Any Deletes the C++ object (at your own risk, my friend!) (shared captured text)
deleteLater function (self) -> Any (shared captured text)
destroyed function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.destroyed; argument details are not documented.
disconnect function (self, signal: Any, receiver: Any, slot: Any) -> bool X.disconnect(signal, receiver, slot) -> bool (shared captured text)
dumpObjectInfo function (self) -> Any (shared captured text)
dumpObjectTree function (self) -> Any (shared captured text)
dynamicPropertyNames function (self) -> Any (shared captured text)
encodeName function (self, fileName: str) -> Any X.encodeName(fileName) -> PythonQt.QtCore.QByteArray (shared captured text)
error function (self) -> Any (shared captured text)
errorString function (self) -> str X.errorString() -> str (shared captured text)
event function (self, event: Any) -> bool X.event(event) -> bool (shared captured text)
eventFilter function (self, watched: Any, event: Any) -> bool X.eventFilter(watched, event) -> bool (shared captured text)
exists function (self) -> bool X.exists() -> bool (shared captured text)
fileName function (self) -> str X.fileName() -> str (shared captured text)
findChild function (self, type: Any, name: Any) -> Any X.findChild(type, name) -> PythonQt.private.QObject (shared captured text)
findChildren function (self, type: Any, name: Any) -> tuple X.findChildren(type, name) -> tuple (shared captured text)
flush function (self) -> bool X.flush() -> bool (shared captured text)
getChar function (self, c: Any) -> bool X.getChar(c) -> bool (shared captured text)
handle function (self) -> int X.handle() -> int (shared captured text)
help function (self, *args: Any, **kwargs: Any) -> Any Shows the help of available methods for this class (shared captured text)
inherits function (self, *args: Any, **kwargs: Any) -> Any Returns if the class inherits or is of given type name (shared captured text)
installEventFilter function (self, filterObj: Any) -> Any (shared captured text)
isOpen function (self) -> bool X.isOpen() -> bool (shared captured text)
isReadable function (self) -> bool X.isReadable() -> bool (shared captured text)
isSequential function (self) -> bool X.isSequential() -> bool (shared captured text)
isSignalConnected function (self, signal: Any) -> bool X.isSignalConnected(signal) -> bool (shared captured text)
isTextModeEnabled function (self) -> bool X.isTextModeEnabled() -> bool (shared captured text)
isWidgetType function (self) -> bool X.isWidgetType() -> bool (shared captured text)
isWindowType function (self) -> bool X.isWindowType() -> bool (shared captured text)
isWritable function (self) -> bool X.isWritable() -> bool (shared captured text)
killTimer function (self, id: Any) -> Any (shared captured text)
link function (self, newName: str) -> bool X.link(newName) -> bool (shared captured text)
map function (self, offset: Any, size: Any, arg2: flags) -> int X.map(offset, size, flags) -> int (shared captured text)
metaObject function (self) -> Any X.metaObject() -> PythonQt.QtCore.QMetaObject (shared captured text)
moveToThread function (self, thread: Any) -> Any (shared captured text)
objectName attribute Any (shared captured text)
objectNameChanged function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.objectNameChanged; argument details are not documented.
open function (self, arg0: flags) -> bool X.open(flags) -> bool (shared captured text)
openMode function (self) -> Any (shared captured text)
parent function (self) -> Any X.parent() -> PythonQt.private.QObject (shared captured text)
peek function (self, maxlen: Any) -> Any X.peek(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
permissions function (self) -> Any (shared captured text)
pos function (self) -> int X.pos() -> int (shared captured text)
property function (self, name: Any) -> Any X.property(name) -> object (shared captured text)
putChar function (self, c: Any) -> bool X.putChar(c) -> bool (shared captured text)
read function (self, maxlen: Any) -> Any X.read(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
readAll function (self) -> Any X.readAll() -> PythonQt.QtCore.QByteArray (shared captured text)
readChannelFinished function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.readChannelFinished; argument details are not documented.
readData function (self, data: Any, maxlen: Any) -> int X.readData(data, maxlen) -> int (shared captured text)
readLine function (self, maxlen: Any) -> Any X.readLine(maxlen) -> PythonQt.QtCore.QByteArray (shared captured text)
readLineData function (self, data: Any, maxlen: Any) -> int X.readLineData(data, maxlen) -> int (shared captured text)
readyRead function (self, *args: Any, **kwargs: Any) -> Any Native PythonQt.Qt.QFile.readyRead; argument details are not documented.
remove function (self) -> bool X.remove() -> bool (shared captured text)
removeEventFilter function (self, obj: Any) -> Any (shared captured text)
rename function (self, newName: str) -> bool X.rename(newName) -> bool (shared captured text)
reset function (self) -> bool X.reset() -> bool (shared captured text)
resize function (self, sz: int) -> bool X.resize(sz) -> bool (shared captured text)
seek function (self, offset: Any) -> bool X.seek(offset) -> bool (shared captured text)
sender function (self) -> Any X.sender() -> PythonQt.private.QObject (shared captured text)
senderSignalIndex function (self) -> int X.senderSignalIndex() -> int (shared captured text)
setErrorString function (self, errorString: Any) -> Any (shared captured text)
setFileName function (self, name: str) -> None (shared captured text)
setObjectName function (self, name: Any) -> Any (shared captured text)
setOpenMode function (self, openMode: Any) -> Any (shared captured text)
setParent function (self, parent: Any) -> Any (shared captured text)
setPermissions function (self, permissionSpec: Any) -> bool X.setPermissions(permissionSpec) -> bool (shared captured text)
setProperty function (self, name: Any, value: Any) -> bool X.setProperty(name, value) -> bool (shared captured text)
setTextModeEnabled function (self, enabled: Any) -> Any (shared captured text)
signalsBlocked function (self) -> bool X.signalsBlocked() -> bool (shared captured text)
size function (self) -> int X.size() -> int (shared captured text)
startTimer function (self, interval: Any, timerType: Any) -> int X.startTimer(interval, timerType) -> int (shared captured text)
symLinkTarget function (self) -> str X.symLinkTarget() -> str (shared captured text)
thread function (self) -> Any (shared captured text)
timerEvent function (self, event: Any) -> Any (shared captured text)
tr function (self, text: Any, ambig: Any, n: Any) -> str X.tr(text, ambig, n) -> str (shared captured text)
ungetChar function (self, c: Any) -> Any (shared captured text)
unmap function (self, address: Any) -> bool X.unmap(address) -> bool (shared captured text)
unsetError function (self) -> Any (shared captured text)
waitForBytesWritten function (self, msecs: Any) -> bool X.waitForBytesWritten(msecs) -> bool (shared captured text)
waitForReadyRead function (self, msecs: Any) -> bool X.waitForReadyRead(msecs) -> bool (shared captured text)
write function (self, data: Any) -> int X.write(data) -> int (shared captured text)
writeData function (self, data: Any, len: Any) -> int X.writeData(data, len) -> int (shared captured text)