100-Data reading and writing and file management-Basic classes for data reading and writing-File information QFileInfo

File information QFileInfo

File information QFileInfo is used to query file information, such as the relative path of the file, the absolute path, the file size, the file permission, the creation and modification time of the file, etc.

The method of creating a file information object with the QFileInfo class is as follows, where str is the file that needs to obtain file information, and QFileInfo(QDir, str) means to use the str file under the QDir path to create a file information object

from PySide6.QtCore import QFileInfo

QFileInfo(self) -> None
QFileInfo(dir: Union[PySide6.QtCore.QDir,str],file: Union[str,bytes,os.PathLike])-> None
QFileInfo(file: Union[str,bytes,os.PathLike])-> None
QFileInfo(file: PySide6.QtCore.QFileDevice) -> None
QFileInfo(fileinfo: PySide6.QtCore.QFileInfo) -> None

File information QFileInfo description

QFileInfo provides information about the file’s name and location (path) in the file system, access permissions, and whether it is a directory or a symbolic link. Also provides the size and last modified/read time of the file. QFileInfo can also be used to obtain information about Qt resources.

QFileInfo can point to files with relative or absolute file paths. Absolute file paths start with the directory separator “/” (or with a drive specification on Windows). A relative filename starts with a directory name or filename and specifies a path relative to the current working directory. An example of an absolute path is the string “/tmp/quartz”. A relative path might look like “src/fatlib”. You can use the function isRelative() to check whether QFileInfo is using a relative or absolute file path. You can call the function makeAbsolute() to convert a relative QFileInfo path to an absolute path.

Paths starting with a colon (:) are always considered absolute, since they denote a QResource.

The file handled by QFileInfo is set using setFile() in the constructor or later. Use exists() to see if the file exists, and size() to get its size.

The type of the file is obtained through isFile(), isDir() and isSymLink(). What the function does is provide the name of the file the symbolic link points to.

On Unix (including macOS and iOS), the property getter functions in this class return properties such as the time and size of the target file, not the symbolic link, because Unix handles symbolic links transparently. Opening a symbolic link with QFile effectively opens the target of the link. For example:

#ifdef Q_OS_UNIX
info1 = QFileInfo("/home/bob/bin/untabify")
info1.isSymLink()# returns true
info1.absoluteFilePath()# returns"/home/bob/bin/untabify"
info1. size()# returns 56201
info1.symLinkTarget()# returns"/opt/pretty + + /bin/untabify"
info2 = QFileInfo(info1. symLinkTarget())
info2.isSymLink()# returns false
info2.absoluteFilePath()# returns"/opt/pretty + + /bin/untabify"
info2. size()# returns 56201
#endif

On Windows, shortcuts (.lnk files) are currently treated as symbolic links. As on Unix systems, the property getter returns the size of the object file, not the .lnk file itself. This behavior is deprecated and may be removed in a future version of Qt, after which .lnk files will be treated as regular files.

#ifdef Q_OS_WIN
info1 = QFileInfo("C:\Users\Bob\untabify.lnk")
info1.isSymLink()# returns true
info1.absoluteFilePath()# returns"C:/Users/Bob/untabify.lnk"
info1. size()# returns 63942
info1.symLinkTarget()# returns"C:/Pretty + + /untabify"
info2 = QFileInfo(info1. symLinkTarget())
info2.isSymLink()# returns false
info2.absoluteFilePath()# returns"C:/Pretty + + /untabify"
info2. size()# returns 63942
#endif

Elements of a filename can be extracted with path() and fileName(). Parts of fileName() can be extracted with baseName() , suffix() or completeSuffix() . QFileInfo objects for directories created by Qt classes will have no trailing file separator. If you wish to use a trailing delimiter in your own file info objects, simply append a delimiter to the filename given to the constructor or setFile().

The date of the file is returned by birthTime(), lastModified(), lastRead(), and fileTime(). Information about file access permissions is obtained through isReadable(), isWritable(), and isExecutable(). Ownership of a file can be obtained from owner(), ownerId(), group(), and groupId(). You can check the permissions and ownership of a file in one statement using the permission() function.

On NTFS filesystems, ownership and permission checks are disabled by default for performance reasons. To enable it, include the following line:

Q_CORE_EXPORT = extern()

Then turn permission checking on and off by incrementing and decrementing qt_ntfs_Permission_lookup by 1.

qt_ntfs_permission_lookup + + # turn checking on
qt_ntfs_permission_lookup-- # turn it off again

Since this is a non-atomic global variable, it is safe to increment or decrement qt_ntfs_permission_lookup only before any thread other than the main thread starts or after each thread other than the main thread ends.

Performance issues

Some functions of QFileInfo query the file system, but for performance reasons, some functions only operate on the filename itself. For example: To return an absolute path relative to a filename, absolutePath() must query the file system. However, the path() function can handle filenames directly, so it is faster.

To improve performance, QFileInfo caches information about files.

Because files can be changed by other users or programs, or even by other parts of the same program, there is a function to refresh file information: refresh(). If you want to turn off QFileInfo’s caching and force it to access the file system every time information is requested from it, call setCaching(false). Use stat() if you want to ensure all information is read from the file system.

Platform specific issues

On Android, there are some limitations when dealing with content URIs:

  • Prompt the user that access permissions may be required through QFileDialog, which implements Android’s native file selector.
  • Designed to follow Scoped storage guidelines, such as using application-specific directories instead of other public external directories. See also storage best practices for details.
  • Due to the design of Qt APIs (e.g. QFile), it is not possible to fully integrate the latter API with Android’s MediaStore API.

File information QFileInfo method

The common methods of QFileInfo are shown in the table, the main methods shown in the table are as follows: reset the file to obtain file information.

  • You can set the file to get the file information when creating the QFileInfo object, or use
    • setFile(dir: Union[QDir, str], file: str)
    • setFile(file: Union[str,bytes])
    • setFile(file:QFileDevice)
  • QFileInfo provides a refresh() function for re-reading file information.
    • If you want to turn off the caching function to ensure that you can get the latest information every time you access the file, you can use the setCaching(False) method to complete the setting.
  • Use the absoluteFilePath() method to get the absolute path and file name;
    • Use the absolutePath() method to get the absolute path without the file name;
    • Use the fileName() method to get the file name, including the extension, without the path.
    • When there are multiple . in the file name, use the suffix() method to get the extension, excluding .
    • Use the completeSuffx() method to get the file name after the first ., including the extension.
  • Use the exists() method to get whether the file exists Use the exists(str) method to get whether the specified file exists
  • Use the birthTime() method to get the creation time QDateTime, if it is a shortcut file, return the creation time of the target file;
  • Use the lastModified() method to get the last modification time QDateTime;
    • Use the lastRead() method to get the last read time QDateTime.
  • You can use a relative path to point to a file, or you can use an absolute path to point to a file.
    • Use the isRelative() method to get whether it is a relative path;
    • Use the makeAbsolute() method to convert to an absolute path. If the return value is False, it means that it is already an absolute path.
  • Use the isFile() method to get whether it is a file,
    • Use the isDir() method to get whether it is a path
    • Use the isShortcut() method to get whether it is a shortcut (link),
    • Use the isReadable() method to get whether the file is readable,
    • Use the isWritable() method to get whether the file is writable.
QFilelnfo method and parameter type return value type description
getFile(dir: Union[QDir,sur], file:str) None This is an overloaded function.
Sets the files for which QFileInfo provides information to the files in the directory dir.
If the file contains relative paths, QFileInfo will also have relative paths.
setFile(file: Union[str, bytes]) None Set the file for which QFileInfo provides information to the file.
The file can also include absolute or relative file paths. Absolute paths start with a directory separator (e.g. “/” under Unix) or a drive specification (under Windows). A relative filename starts with a directory name or filename and specifies a path relative to the current directory.
example:
info = QFileInfo(“/usr/bin/env”)
path = info.absolutePath()# path = /usr/bin
base = info. baseName()# base = env
info.setFile(“/etc/hosts”)
path = info.absolutePath()# path = /etc
base = info.baseName()# base = hosts
setFile(file: PySide6.QtCore.QFileDevice) None This is an overloaded function.
Sets the file for which QFileInfo provides information to the file.
If the file contains relative paths, QFileInfo will also have relative paths.
setCaching(bool) None If enable is true, enable caching of file information. If enabled is false, caching is disabled.
When caching is enabled, QFileInfo reads file information from the file system the first time it is needed, but usually not later.
Caching is enabled by default.
refresh() None Refresh information about the file, i.e. read from the filesystem the next time the cached attribute is fetched information.
absoluteDir() QDir Returns the absolute path of the file in the form of a QDir object.
__ne__(fileinfo:PySide6.QtCore.QFileInfo) bool If this QFileInfo object Returns true if the referenced file is different from the file specified by fileinfo; otherwise returns false.
__eq__(fileinfo:PySide6.QtCore.QFileInfo) bool If this QFileInfo object Returns true to refer to a file at the same location as fileinfo; otherwise returns false.
Note that the result of comparing two empty QFileInfo objects (containing no file references (non-existent or empty file paths)) is undefined.
This will not compare two different symlinks pointing to the same file.
On Windows, long and short filenames referencing the same file are treated as referring to different files.
absoluteFilePath() str Returns an absolute path including the file name.
An absolute pathname consists of the full path and filename. On Unix it always starts with the root directory “/”. On Windows, this will always start with “D:/”, where D is the drive letter, except for network shares that are not mapped to a drive letter, in which case the path will start with “//sharename/”. QFileInfo will capitalize the drive letter. Note that QDir doesn’t do this. The code snippet below shows this.
QFileInfo fi(“c:/temp/foo”); => fi.absoluteFilePath() => “C:/temp/foo”
This function returns the same value as filePath() unless isRelative() is true. In contrast to canonicalFilePath(), symbolic links or redundant “.” or “…” elements are not necessarily removed.
The behavior of this function is undefined if filePath() is null.
absolutePath() str Returns the absolute path of the file path. This does not include the filename.
On Unix, absolute paths always start with the root directory “/”. On Windows, this will always start with “D:/”, where D is the drive letter, except for network shares that are not mapped to a drive letter, in which case the path will start with “//sharename/”.
In contrast to canonicalPath(), symbolic links or redundant “.” or “…” elements are not necessarily removed.
baseName() str Returns the basename of the file without the path.
The base name consists of all characters in the file up to (but not including) the first “” character
example:
fi = QFileInfo(“/tmp/archive.tar.gz”)
base = fi. baseName()# base = “archive”
The basename of the file is evaluated equally on all platforms, regardless of the file naming convention (e.g. “.bashrc” on Unix has an empty basename with a “bashrc” suffix).
caching() bool Returns true if caching is enabled; otherwise returns false.
completeBaseName() str Returns the complete basename of the file without the path.
The full basename consists of all characters in the file up to (but not including) the last “” character
example:
fi = QFileInfo(“/tmp/archive.tar.gz”)
base = fi.completeBaseName()# base = “archive.tar”
completeSuffix() str Returns the file’s Full suffix (extension).
The full suffix consists of all characters in the file after (but not including) the first “.
example:
fi = QFileInfo(“/tmp/archive.tar.gz”)
ext = fi.completeSuffix()# ext = “tar.gz”
suffix() str returns the file suffix (extension).
The suffix consists of all characters after (but not including) the last “.” in the file.
example:
fi = QFileInfo(“/tmp/archive.tar.gz”)
ext = fi. suffix()# ext = “gz”
The suffix of the file is calculated equally on all platforms, regardless of the file naming convention (e.g. “.bashrc” on Unix has an empty basename and the suffix is “bashrc”).
completeSufix() str Get the file name after the first ., including extension
fileName() str Returns the name of the file, not including the path.
example:
fi = QFileInfo(“/tmp/archive.tar.gz”)
name = fi.fileName()# name = “archive.tar.gz”
Note that if this QFileInfo object is given a path ending in a slash, the filename is considered to be empty.
swap(other:QFileInfo) Exchange this file information with other file information. This function is very fast and never fails.
path() str Returns the path of the file. This does not include the filename.
Note that if this QFileInfo object is given a path ending in a slash, the filename is considered empty and this function will return the entire path.
filePath() str Returns the file name, including the path (it can be an absolute path or a relative path) .
canonicalFilePath() str Returns the canonical path containing the filename, i.e. no symlinks or redundant “. ” or absolute path to a “…” element.
If the file does not exist, canonicalFilePath() will return an empty string.
acanonicalPath() str Returns the path canonical path (excluding the filename) of the file, i.e. no symlinks or Absolute paths to redundant “.” or “…” elements.
If the file does not exist, canonicalPath() will return an empty string.
birthTime() QDateTime Returns the date and time the file was created/generated.
If the file birth time is not available, this function will return an invalid QDateTime.
If the file is a symbolic link, returns the time of the target file (not the symbolic link).
bundleName() str Returns the name of the bundle.
On macOS and iOS, if path is bundle(), returns the correct localized name of the bundle. On all other platforms, an empty QString is returned.
example:
fi = QFileInfo(“/Applications/Safari.app”)
bundle = fi.bundleName()# name = “Safari”
lastModified() QDaLeTime Return to the last modified file date and local time.
If the file is a symbolic link, returns the time of the target file (not the symbolic link).
lastRead() QDateTime Returns the date and local time when the file was last read (accessed).
On platforms without this information, return the same information as lastModified().
If the file is a symbolic link, returns the time of the target file (not the symbolic link).
adir() QDir Get the path of the parent class
dir() PySide6.QtCore.QDir Returns the path of the object’s parent directory as a QDir object.
The returned QDir always corresponds to the object’s parent directory, even if the QFileInfo represents a directory.
For each of the following, dir() returns QDir”~/examples/191697″.
fileInfo1 = QFileInfo(“~/examples/191697/.”)
fileInfo2 = QFileInfo(“~/examples/191697/…”)
fileInfo3 = QFileInfo(“~/examples/191697/main.cpp”)
For each of the following, dir() will return QDir”.”.
fileInfo4 = QFileInfo(“.”)
fileInfo5 = QFileInfo(“…”)
fileInfo6 = QFileInfo(“main.cpp”)
group() str Returns the group of the file. On Windows, on systems where the file has no group, or if an error occurs, an empty string will be returned.
This function can be time consuming (in milliseconds) under Unix.
If the file is a symbolic link, this function returns the owning group of the target (not the symbolic link).
groupId() int Returns the id of the group to which the file belongs.
On Windows and systems where the file has no groups, this function always returns (uint)-2.
If the file is a symlink, this function will return the id of the group owning the target (not the symlink).
isAbsolute() bool If the file path is an absolute path, return true, otherwise return false (that is, the path is relative path).
isAlias() bool Returns true if this object points to an alias; otherwise returns false.
Aliases only exist on macOS. They are treated as regular files, so opening an alias will open the file itself. In order to open a file or directory referenced by an alias, use symLinkTarget().
isBundle() bool If this object points to a bundle or a symlink to a bundle on macOS and iOS , returns true; otherwise returns false.
If the file is a symlink, then this function will return true if the target is a bundle (not a symlink).
isDir() bool Returns true if this object points to a directory or points to a symbolic link pointing to a directory; otherwise returns false.
If the file is a symlink, then this function will return true if the target is a directory (not a symlink).
isExecutable() bool Returns true if the file is executable; otherwise returns false.
If the file is a symlink, then this function will return true if the target is an executable (not a symlink).
isFile() bool Returns true if this object points to a file or a symbolic link pointing to a file. Returns false if the object points to something other than a file, such as a directory.
If the file is a symbolic link, then this function will return true if the target is a regular file (not a symbolic link).
isHidden() bool returns true if this is a “hidden” file; false otherwise .
This function returns true for the special entries “.” and “…” on Unix, even if entryList threatens them as shown. Note that since this function checks the filename, on Unix it will check the name of the symlink if this file is a symlink, not the name of the target.
On Windows, this function will return true if the target file is hidden (rather than a symlink).
isJunction() bool If the object points to a junction, return true; otherwise return false.
Links exist only in Windows’ NTFS file system and are usually created by the mklink command. They can be thought of as symbolic links to directories, and can only be created for absolute paths on local volumes.
isNativePath() bool Returns true if the file path can be used directly with the native API. Returns false if the file is supported by Qt’s internal virtual file system (such as the Qt resource system).
Native paths may still require conversion of path separators and character encodings, depending on the platform and input requirements of the native API.
isReadable() bool Returns true if the user can read the file; otherwise returns false.
If the file is a symlink, then this function will return true if the target is readable (not a symlink).
If NTFS permission checking is not enabled, the results on Windows will simply reflect whether the file exists.
isRelative() bool If the file path is a relative path, return true, otherwise return false (that is, the path is absolute path). (For example, under Unix, a path is absolute if it starts with “/”).
Paths starting with a colon (:) are always considered absolute, since they denote a QResource.
isRoot() bool If the object points to a directory or points to a symbolic link to a directory, and the directory is the root directory, returns true; otherwise returns false.
isShortcut() bool Returns true if this object points to a shortcut; otherwise returns false.
Shortcuts exist only on Windows, usually as .lnk files. For example, shortcuts (*.lnk files) will return true on Windows, but false on Unix (including macOS and iOS).
Shortcut (.lnk) files are treated as regular files. Opening these files will open the .lnk file itself. In order to open the file referenced by the shortcut, it must use symLinkTarget() on the shortcut.
isShorteut() bool Get whether it is a shortcut (link)
isSymLink() bool Returns true if this object points to a symbolic link, shortcut or alias; otherwise returns false.
Symbolic links exist on Unix (including macOS and iOS) and Windows, and are usually created by the ln -s or mklink commands, respectively. Opening a symbolic link effectively opens the target of the link.
Also, will return true for shortcuts (*.lnk files) on Windows and aliases on macOS. This behavior is deprecated and may change in future versions of Qt. Opening a shortcut or alias will open the .lnk or alias file itself.
example:
info = QFileInfo(fileName)
if info.isSymLink():
fileName = info.symLinkTarget()
exists() will return false if the symbolic link points to a file that does not exist.
isSymbolicLink() bool Returns true if this object points to a symbolic link; otherwise returns false.
Symbolic links exist on Unix (including macOS and iOS) and Windows (NTFS symbolic links), and are usually created by the ln -s or mklink commands, respectively.
Unix handles symbolic links transparently. Opening a symbolic link effectively opens the target of the link.
Unlike isSymLink(), shortcuts (*.lnk files) on Windows and aliases on macOS will return false. Use isShortcut() and isAlias() instead.
exists() will return false if the symbolic link points to a file that does not exist.
isWritable() bool Returns true if the user can write to the file; otherwise returns false.
If the file is a symlink, then this function will return true if the target is writable (not a symlink).
If NTFS permission checking is not enabled, the results on Windows will only reflect whether the file is marked read-only.
junctionTarget() str Resolves an NTFS junction to the path it refers to.
Returns the absolute path of the directory pointed to by the NTFS connection, or an empty string if the object is not an NTFS connection.
There is no guarantee that a directory named by an NTFS connection actually exists.
makeAbsolute() bool If the path of the file is not already in the form of an absolute path, convert it to an absolute path . Return true to indicate that the path has been converted; otherwise return false to indicate that the path is already an absolute path.
metadataChangeTime() PySide6.QtCore.QDateTime Returns the date and time when the file metadata was changed. Metadata changes happen when a file is created, but also when a user writes or sets inode information (for example, changing file permissions).
If the file is a symbolic link, returns the time of the target file (not the symbolic link).
owner() str Returns the owner of the file. On systems where the file has no owner, or if an error occurs, an empty string will be returned.
This function can be time consuming (in milliseconds) under Unix. On Windows, it will return an empty string unless NTFS permission checking is enabled.
If the file is a symlink, this function will return the owner of the target (not the symlink).
ownerld() int Returns the id of the file owner.
On Windows and systems where the file has no owner, this function returns ((uint)-2).
If the file is a symlink, this function will return the id of the target owner (not the symlink).
size() int Returns the file size in bytes. Returns 0 if the file does not exist or could not be extracted.
If the file is a symbolic link, returns the size of the target file (not the symbolic link).
stat() Read all attributes from the file system.
This is useful when collecting information about the file system in a worker thread and then passing it to the UI in the form of a cached QFileInfo instance.
symLinkTarget() str Returns the absolute path of the file or directory pointed to by the symbolic link, if the object is not a symbolic link, returns an empty string.
This name may not represent an existing file; it’s just a string. exists() will return true if the symlink points to an existing file.
[static]exists(file: str) bool If the specified file exists, return true; otherwise return false .
[static]exists() bool Returns true if the file exists; otherwise returns false.