QFile — PyQt Documentation v5.15.7 (original) (raw)
PyQt5.QtCore.QFile
Inherits from QFileDevice.
Inherited by QTemporaryFile.
Description¶
The QFile class provides an interface for reading from and writing to files.
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 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 codecForLocale() for details). This can be changed using 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 isWritable() 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 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.
Methods¶
__init__()
Constructs a QFile object.
__init__(str)
Constructs a new file object to represent the file with the given name.
__init__(QObject)
Constructs a new file object with the given parent.
__init__(str, QObject)
Constructs a new file object with the given parent to represent the file with the specified name.
copy(str) → bool
Copies the file currently specified by fileName() to a file called newName. Returns true
if successful; otherwise returns false
.
Note that if a file with the name newName already exists, returns false
(i.e. QFile will not overwrite it).
The source file is closed before it is copied.
@staticmethod
copy(str, str) → bool
This is an overloaded function.
Copies the file fileName to newName. Returns true
if successful; otherwise returns false
.
If a file with the name newName already exists, copy() returns false
(i.e., QFile will not overwrite it).
@staticmethod
decodeName(Union[QByteArray, bytes, bytearray]) → str
TODO
@staticmethod
decodeName(str) → str
TODO
@staticmethod
encodeName(str) → QByteArray
TODO
exists() → bool
This is an overloaded function.
Returns true
if the file specified by fileName() exists; otherwise returns false
.
See also
@staticmethod
exists(str) → bool
Returns true
if the file specified by fileName exists; otherwise returns false
.
Note: If fileName is a symlink that points to a non-existing file, false is returned.
fileName() → str
Returns the name set by setFileName() or to the QFile constructors.
link(str) → bool
Creates a link named linkName that points to the file currently specified by fileName(). What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true
if successful; otherwise returns false
.
This function will not overwrite an already existing entity in the file system; in this case, link()
will return false and set error() to return RenameError.
Note: To create a valid link on Windows, linkName must have a .lnk
file extension.
@staticmethod
link(str, str) → bool
This is an overloaded function.
Creates a link named linkName that points to the file fileName. What a link is depends on the underlying filesystem (be it a shortcut on Windows or a symbolic link on Unix). Returns true
if successful; otherwise returns false
.
moveToTrash() → bool
TODO
@staticmethod
moveToTrash(str) → (bool, str)
TODO
open(Union[OpenMode, OpenModeFlag]) → bool
TODO
open(int, Union[OpenMode, OpenModeFlag], handleFlags: Union[FileHandleFlags, FileHandleFlag] = QFileDevice.FileHandleFlag.DontCloseHandle) → bool
TODO
permissions() → Permissions
See also
@staticmethod
permissions(str) → Permissions
This is an overloaded function.
Returns the complete OR-ed together combination of QFile::Permission for fileName.
remove() → bool
Removes the file specified by fileName(). Returns true
if successful; otherwise returns false
.
The file is closed before it is removed.
@staticmethod
remove(str) → bool
This is an overloaded function.
Removes the file specified by the fileName given.
Returns true
if successful; otherwise returns false
.
rename(str) → bool
Renames the file currently specified by fileName() to newName. Returns true
if successful; otherwise returns false
.
If a file with the name newName already exists, returns false
(i.e., QFile will not overwrite it).
The file is closed before it is renamed.
If the rename operation fails, Qt will attempt to copy this file’s contents to newName, and then remove this file, keeping only newName. If that copy operation fails or this file can’t be removed, the destination file newName is removed to restore the old state.
@staticmethod
rename(str, str) → bool
This is an overloaded function.
Renames the file oldName to newName. Returns true
if successful; otherwise returns false
.
If a file with the name newName already exists, rename() returns false
(i.e., QFile will not overwrite it).
resize(int) → bool
TODO
@staticmethod
resize(str, int) → bool
This is an overloaded function.
Sets fileName to size (in bytes) sz. Returns true
if the resize succeeds; false otherwise. If sz is larger than fileName currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.
Warning: This function can fail if the file doesn’t exist.
setFileName(str)
Sets the name of the file. The name can have no path, a relative path, or an absolute path.
Do not call this function if the file has already been opened.
If the file name has no path or a relative path, the path used will be the application’s current directory path at the time of the :sip:ref:`~PyQt5.QtCore.QFile.open` call.
Example:
QFile file;
QDir::setCurrent("/tmp");
file.setFileName("readme.txt");
QDir::setCurrent("/home");
file.open(QIODevice::ReadOnly); // opens "/home/readme.txt" under Unix
Note that the directory separator “/” works for all operating systems supported by Qt.
setPermissions(Union[Permissions, Permission]) → bool
TODO
@staticmethod
setPermissions(str, Union[Permissions, Permission]) → bool
TODO
size() → int
TODO
symLinkTarget() → str
TODO
@staticmethod
symLinkTarget(str) → str
TODO