PySide6.QtCore.QFile¶
- class QFile¶
- The - QFileclass provides an interface for reading from and writing to files. More…- Inherited by: - QTemporaryFile- Synopsis¶- Methods¶- def - __init__()
- def - copy()
- def - exists()
- def - link()
- def - moveToTrash()
- def - open()
- def - remove()
- def - rename()
- def - setFileName()
- def - symLinkTarget()
 - Static functions¶- def - copy()
- def - decodeName()
- def - encodeName()
- def - exists()
- def - link()
- def - moveToTrash()
- def - permissions()
- def - remove()
- def - rename()
- def - resize()
- def - setPermissions()
- def - symLinkTarget()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - QFileis an I/O device for reading and writing text and binary files and resources . A- QFilemay be used by itself or, more conveniently, with a- QTextStreamor- QDataStream.- The file name is usually passed in the constructor, but it can be set at any time using - setFileName().- QFileexpects 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- QFileInfoand- QDir.)- The file is opened with - open(), closed with- close(), and flushed with- flush(). Data is usually read and written using- QDataStreamor- QTextStream, but you can also call the- QIODevice-inherited functions- read(),- readLine(),- readAll(),- write().- QFilealso 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: - file = QFile("in.txt") if not file.open(QIODevice.ReadOnly | QIODevice.Text): return while not file.atEnd(): line = file.readLine() process_line(line) - The - Textflag passed to- open()tells Qt to convert Windows-style line terminators (”\r\n”) into C++-style terminators (”\n”). By default,- QFileassumes 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 - QTextStreamto read a text file line by line:- file = QFile("in.txt") if not file.open(QIODevice.ReadOnly | QIODevice.Text): return in = QTextStream(file) while not in.atEnd(): line = in.readLine() process_line(line) - QTextStreamtakes care of converting the 8-bit data stored on disk into a 16-bit Unicode- QString. By default, it assumes that the file is encoded in UTF-8. This can be changed using- setEncoding().- To write text, we can use operator<<(), which is overloaded to take a - QTextStreamon the left and various data types (including- QString) on the right:- file = QFile("out.txt") if not file.open(QIODevice.WriteOnly | QIODevice.Text): return out = QTextStream(file) out << "The magic number is: " << 49 << "\n" - QDataStreamis similar, in that you can use operator<<() to write data and operator>>() to read it back. See the class documentation for details.- Signals¶- Unlike other - QIODeviceimplementations, such as QTcpSocket,- QFiledoes not emit the- aboutToClose(),- bytesWritten(), or- readyRead()signals. This implementation detail means that- QFileis not suitable for reading and writing certain types of files, such as device files on Unix platforms.- Platform Specific Issues¶- Qt APIs related to I/O use UTF-16 based QStrings to represent file paths. Standard C++ APIs ( - <cstdio>or- <iostream>) or platform-specific APIs however often need a 8-bit encoded path. You can use- encodeName()and- decodeName()to convert between both representations.- 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- QTextStreamto read- /proc/modulesline by line:- file = QFile("/proc/modules") if not file.open(QIODevice.ReadOnly | QIODevice.Text): return in = QTextStream(file) line = in.readLine() while not line.isNull(): process_line(line) line = in.readLine() - File permissions are handled differently on Unix-like systems and Windows. In a non - writabledirectory 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.- 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.
 - __init__()¶
 - Constructs a - QFileobject.- __init__(parent)
- Parameters:
- parent – - QObject
 
 - Constructs a new file object with the given - parent.- __init__(name)
- Parameters:
- name – str 
 
 - Constructs a new file object to represent the file with the given - name.- Note - In versions up to and including Qt 6.8, this constructor is implicit, for backward compatibility. Starting from Qt 6.9 this constructor is unconditionally - explicit. Users can force this constructor to be- expliciteven in earlier versions of Qt by defining the- QT_EXPLICIT_QFILE_CONSTRUCTION_FROM_PATHmacro before including any Qt header.- __init__(name, parent)
- Parameters:
- name – str 
- parent – - QObject
 
 
 - Constructs a new file object with the given - parentto represent the file with the specified- name.- copy(newName)¶
- Parameters:
- newName – str 
- Return type:
- bool 
 
 - Copies the file named - fileName()to- newName.- This file is closed before it is copied. - If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied. - Returns - trueif successful; otherwise returns- false.- Note that if a file with the name - newNamealready exists, copy() returns- false. This means- QFilewill not overwrite it.- Note - On Android, this operation is not yet supported for - contentscheme URIs.- See also - static copy(fileName, newName)
- Parameters:
- fileName – str 
- newName – str 
 
- Return type:
- bool 
 
 - This is an overloaded function. - Copies the file named - fileNameto- newName.- This file is closed before it is copied. - If the copied file is a symbolic link (symlink), the file it refers to is copied, not the link itself. With the exception of permissions, which are copied, no other file metadata is copied. - Returns - trueif successful; otherwise returns- false.- Note that if a file with the name - newNamealready exists,- copy()returns- false. This means- QFilewill not overwrite it.- static decodeName(localFileName)¶
- Parameters:
- localFileName – - QByteArray
- Return type:
- str 
 
 - This does the reverse of - encodeName()using- localFileName.- See also - static decodeName(localFileName)
- Parameters:
- localFileName – str 
- Return type:
- str 
 
 - This is an overloaded function. - Returns the Unicode version of the given - localFileName. See- encodeName()for details.- static encodeName(fileName)¶
- Parameters:
- fileName – str 
- Return type:
 
 - Converts - fileNameto an 8-bit encoding that you can use in native APIs. On Windows, the encoding is the one from active Windows (ANSI) codepage. On other platforms, this is UTF-8, for macOS in decomposed form (NFD).- See also - exists()¶
- Return type:
- bool 
 
 - This is an overloaded function. - Returns - trueif the file specified by- fileName()exists; otherwise returns- false.- See also - fileName()- setFileName()- static exists(fileName)
- Parameters:
- fileName – str 
- Return type:
- bool 
 
 - Returns - trueif the file specified by- fileNameexists; otherwise returns- false.- Note - If - fileNameis a symlink that points to a non-existing file, false is returned.- link(newName)¶
- Parameters:
- newName – str 
- Return type:
- bool 
 
 - Creates a link named - linkNamethat 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- trueif 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, - linkNamemust have a- .lnkfile extension.- See also - static link(fileName, newName)
- Parameters:
- fileName – str 
- newName – str 
 
- Return type:
- bool 
 
 - This is an overloaded function. - Creates a link named - linkNamethat 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- trueif successful; otherwise returns- false.- See also - moveToTrash()¶
- Return type:
- bool 
 
 - Moves the file specified by - fileName()to the trash. Returns- trueif successful, and sets the- fileName()to the path at which the file can be found within the trash; otherwise returns- false.- The time for this function to run is independent of the size of the file being trashed. If this function is called on a directory, it may be proportional to the number of files being trashed. If the current - fileName()points to a symbolic link, this function will move the link to the trash, possibly breaking it, not the target of the link.- This function uses the Windows and macOS APIs to perform the trashing on those two operating systems. Elsewhere (Unix systems), this function implements the FreeDesktop.org Trash specification version 1.0. - Note - When using the FreeDesktop.org Trash implementation, this function will fail if it is unable to move the files to the trash location by way of file renames and hardlinks. This condition arises if the file being trashed resides on a volume (mount point) on which the current user does not have permission to create the - .Trashdirectory, or with some unusual filesystem types or configurations (such as sub-volumes that aren’t themselves mount points).- Note - On systems where the system API doesn’t report the location of the file in the trash, - fileName()will be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.- static moveToTrash(fileName[, pathInTrash=None])
- Parameters:
- fileName – str 
- pathInTrash – str 
 
- Return type:
- bool 
 
 - This is an overloaded function. - Moves the file specified by - fileNameto the trash. Returns- trueif successful, and sets- pathInTrash(if provided) to the path at which the file can be found within the trash; otherwise returns- false.- The time for this function to run is independent of the size of the file being trashed. If this function is called on a directory, it may be proportional to the number of files being trashed. If the current - fileName()points to a symbolic link, this function will move the link to the trash, possibly breaking it, not the target of the link.- This function uses the Windows and macOS APIs to perform the trashing on those two operating systems. Elsewhere (Unix systems), this function implements the FreeDesktop.org Trash specification version 1.0. - Note - When using the FreeDesktop.org Trash implementation, this function will fail if it is unable to move the files to the trash location by way of file renames and hardlinks. This condition arises if the file being trashed resides on a volume (mount point) on which the current user does not have permission to create the - .Trashdirectory, or with some unusual filesystem types or configurations (such as sub-volumes that aren’t themselves mount points).- Note - On systems where the system API doesn’t report the path of the file in the trash, - pathInTrashwill be set to the null string once the file has been moved. On systems that don’t have a trash can, this function always returns false.- open(flags, permissions)¶
- Parameters:
- flags – Combination of - OpenModeFlag
- permissions – Combination of - Permission
 
- Return type:
- bool 
 
 - This is an overloaded function. - If the file does not exist and - modeimplies creating it, it is created with the specified- permissions.- On POSIX systems the actual permissions are influenced by the value of - umask.- On Windows the permissions are emulated using ACLs. These ACLs may be in non-canonical order when the group is granted less permissions than others. Files and directories with such permissions will generate warnings when the Security tab of the Properties dialog is opened. Granting the group all permissions granted to others avoids such warnings. - See also - OpenMode- setFileName()- QT_USE_NODISCARD_FILE_OPEN- open(fd, ioFlags[, handleFlags=QFileDevice.FileHandleFlag.DontCloseHandle])
- Parameters:
- fd – int 
- ioFlags – Combination of - OpenModeFlag
- handleFlags – Combination of - FileHandleFlag
 
- Return type:
- bool 
 
 - This is an overloaded function. - Opens the existing file descriptor - fdin the given- mode.- handleFlagsmay be used to specify additional options. Returns- trueif successful; otherwise returns- false.- When a - QFileis opened using this function, behaviour of- close()is controlled by the AutoCloseHandle flag. If AutoCloseHandle is specified, and this function succeeds, then calling- close()closes the adopted handle. Otherwise,- close()does not actually close the file, but only flushes it.- Warning - If - fdis not a regular file, e.g, it is 0 (- stdin), 1 (- stdout), or 2 (- stderr), you may not be able to- seek(). In those cases,- size()returns- 0. See- isSequential()for more information.- Warning - Since this function opens the file without specifying the file name, you cannot use this - QFilewith a- QFileInfo.- See also - close()- QT_USE_NODISCARD_FILE_OPEN- static permissions(filename)¶
- Parameters:
- filename – str 
- Return type:
- Combination of - Permission
 
 - This is an overloaded function. - Returns the complete OR-ed together combination of QFile::Permission for - fileName.- remove()¶
- Return type:
- bool 
 
 - Removes the file specified by - fileName(). Returns- trueif successful; otherwise returns- false.- The file is closed before it is removed. - See also - static remove(fileName)
- Parameters:
- fileName – str 
- Return type:
- bool 
 
 - This is an overloaded function. - Removes the file specified by the - fileNamegiven.- Returns - trueif successful; otherwise returns- false.- See also - rename(newName)¶
- Parameters:
- newName – str 
- Return type:
- bool 
 
 - Renames the file currently specified by - fileName()to- newName. Returns- trueif successful; otherwise returns- false.- If a file with the name - newNamealready exists, rename() returns- false(i.e.,- QFilewill 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- newNameis removed to restore the old state.- See also - static rename(oldName, newName)
- Parameters:
- oldName – str 
- newName – str 
 
- Return type:
- bool 
 
 - This is an overloaded function. - Renames the file - oldNameto- newName. Returns- trueif successful; otherwise returns- false.- If a file with the name - newNamealready exists,- rename()returns- false(i.e.,- QFilewill not overwrite it).- See also - static resize(filename, sz)¶
- Parameters:
- filename – str 
- sz – int 
 
- Return type:
- bool 
 
 - This is an overloaded function. - Sets - fileNameto size (in bytes)- sz. Returns- trueif the resize succeeds; false otherwise. If- szis larger than- fileNamecurrently is the new bytes will be set to 0, if- szis smaller the file is simply truncated.- setFileName(name)¶
- Parameters:
- name – str 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Sets the - nameof 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 - open()** call.- Example: - file = QFile() 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. - static setPermissions(filename, permissionSpec)¶
- Parameters:
- filename – str 
- permissionSpec – Combination of - Permission
 
- Return type:
- bool 
 
 - This is an overloaded function. - Sets the permissions for - fileNamefile to- permissions.- symLinkTarget()¶
- Return type:
- str 
 
 - This is an overloaded function. - Returns the absolute path of the file or directory a symlink (or shortcut on Windows) points to, or a an empty string if the object isn’t a symbolic link. - This name may not represent an existing file; it is only a string. - exists()returns- trueif the symlink points to an existing file.- See also - fileName()- setFileName()- static symLinkTarget(fileName)
- Parameters:
- fileName – str 
- Return type:
- str 
 
 - Returns the absolute path of the file or directory referred to by the symlink (or shortcut on Windows) specified by - fileName, or returns an empty string if the- fileNamedoes not correspond to a symbolic link.- This name may not represent an existing file; it is only a string. - exists()returns- trueif the symlink points to an existing file.