QFile

Inheritance diagram of QFile

Inherited by: QTemporaryFile

Synopsis

Functions

Virtual functions

Static functions

Detailed Description

The PySide.QtCore.QFile class provides an interface for reading from and writing to files.

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

The file name is usually passed in the constructor, but it can be set at any time using PySide.QtCore.QFile.setFileName() . PySide.QtCore.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 PySide.QtCore.QFile.exists() , and remove a file using PySide.QtCore.QFile.remove() . (More advanced file system related operations are provided by PySide.QtCore.QFileInfo and PySide.QtCore.QDir .)

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

The size of the file is returned by PySide.QtCore.QFile.size() . You can get the current file position using PySide.QtCore.QFile.pos() , or move to a new file position using PySide.QtCore.QFile.seek() . If you’ve reached the end of the file, PySide.QtCore.QFile.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() # A QByteArray
    process_line(line)

The QIODevice.Text flag passed to PySide.QtCore.QFile.open() tells Qt to convert Windows-style line terminators (“rn”) into C++-style terminators (“n”). By default, PySide.QtCore.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 PySide.QtCore.QTextStream to 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() # A QByteArray
    process_line(line)

PySide.QtCore.QTextStream takes care of converting the 8-bit data stored on disk into a 16-bit Unicode PySide.QtCore.QString . By default, it assumes that the user system’s local 8-bit encoding is used (e.g., ISO 8859-1 for most of Europe; see QTextCodec.codecForLocale() for details). This can be changed using setCodec().

To write text, we can use operator<<(), which is overloaded to take a PySide.QtCore.QTextStream on the left and various data types (including PySide.QtCore.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"

PySide.QtCore.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 PySide.QtCore.QFile , PySide.QtCore.QFileInfo , and PySide.QtCore.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 PySide.QtCore.QFile , you can use the PySide.QtCore.QFile.encodeName() and PySide.QtCore.QFile.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 PySide.QtCore.QFile.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 PySide.QtCore.QIODevice.read() . In this case, however, you cannot use PySide.QtCore.QFile.atEnd() to determine if there is more data to read (since PySide.QtCore.QFile.atEnd() will return true for a file that claims to have size 0). Instead, you should either call PySide.QtCore.QIODevice.readAll() , or call PySide.QtCore.QIODevice.read() or PySide.QtCore.QIODevice.readLine() repeatedly until no more data can be read. The next example uses PySide.QtCore.QTextStream to read /proc/modules line 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()

Signals

Unlike other PySide.QtCore.QIODevice implementations, such as PySide.QtNetwork.QTcpSocket , PySide.QtCore.QFile does not emit the PySide.QtCore.QIODevice.aboutToClose() , PySide.QtCore.QIODevice.bytesWritten() , or PySide.QtCore.QIODevice.readyRead() signals. This implementation detail means that PySide.QtCore.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 Linux/Mac OS X and Windows. In a non writable directory on Linux, 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.

class PySide.QtCore.QFile
class PySide.QtCore.QFile(parent)
class PySide.QtCore.QFile(name)
class PySide.QtCore.QFile(name, parent)
Parameters:

Constructs a new file object with the given parent .

Constructs a new file object to represent the file with the given name .

Constructs a new file object with the given parent to represent the file with the specified name .

PySide.QtCore.QFile.FileError

This enum describes the errors that may be returned by the PySide.QtCore.QFile.error() function.

Constant Description
QFile.NoError No error occurred.
QFile.ReadError An error occurred when reading from the file.
QFile.WriteError An error occurred when writing to the file.
QFile.FatalError A fatal error occurred.
QFile.ResourceError  
QFile.OpenError The file could not be opened.
QFile.AbortError The operation was aborted.
QFile.TimeOutError A timeout occurred.
QFile.UnspecifiedError An unspecified error occurred.
QFile.RemoveError The file could not be removed.
QFile.RenameError The file could not be renamed.
QFile.PositionError The position in the file could not be changed.
QFile.ResizeError The file could not be resized.
QFile.PermissionsError The file could not be accessed.
QFile.CopyError The file could not be copied.
PySide.QtCore.QFile.MemoryMapFlags

This enum describes special options that may be used by the PySide.QtCore.QFile.map() function.

Constant Description
QFile.NoOptions No options.
PySide.QtCore.QFile.Permission

This enum is used by the permission() function to report the permissions and ownership of a file. The values may be OR-ed together to test multiple permissions and ownership values.

Constant Description
QFile.ReadOwner The file is readable by the owner of the file.
QFile.WriteOwner The file is writable by the owner of the file.
QFile.ExeOwner The file is executable by the owner of the file.
QFile.ReadUser The file is readable by the user.
QFile.WriteUser The file is writable by the user.
QFile.ExeUser The file is executable by the user.
QFile.ReadGroup The file is readable by the group.
QFile.WriteGroup The file is writable by the group.
QFile.ExeGroup The file is executable by the group.
QFile.ReadOther The file is readable by anyone.
QFile.WriteOther The file is writable by anyone.
QFile.ExeOther The file is executable by anyone.

Warning

Because of differences in the platforms supported by Qt, the semantics of ReadUser , WriteUser and ExeUser are platform-dependent: On Unix, the rights of the owner of the file are returned and on Windows the rights of the current user are returned. This behavior might change in a future Qt version.

Note that Qt does not by default check for permissions on NTFS file systems, as this may decrease the performance of file handling considerably. It is possible to force permission checking on NTFS by including the following code in your source:

extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;

Permission checking is then turned on and off by incrementing and decrementing qt_ntfs_permission_lookup by 1.

qt_ntfs_permission_lookup += 1 // turn checking on
qt_ntfs_permission_lookup += 1 // turn it off again
PySide.QtCore.QFile.copy(newName)
Parameters:newName – unicode
Return type:PySide.QtCore.bool

Copies the file currently specified by PySide.QtCore.QFile.fileName() to a file called newName . Returns true if successful; otherwise returns false.

Note that if a file with the name newName already exists, PySide.QtCore.QFile.copy() returns false (i.e. PySide.QtCore.QFile will not overwrite it).

The source file is closed before it is copied.

static PySide.QtCore.QFile.copy(fileName, newName)
Parameters:
  • fileName – unicode
  • newName – unicode
Return type:

PySide.QtCore.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, PySide.QtCore.QFile.copy() returns false (i.e., PySide.QtCore.QFile will not overwrite it).

static PySide.QtCore.QFile.decodeName(localFileName)
Parameters:localFileName – str
Return type:unicode

This is an overloaded function.

Returns the Unicode version of the given localFileName . See PySide.QtCore.QFile.encodeName() for details.

static PySide.QtCore.QFile.decodeName(localFileName)
Parameters:localFileNamePySide.QtCore.QByteArray
Return type:unicode

This does the reverse of QFile.encodeName() using localFileName .

See also

setDecodingFunction() PySide.QtCore.QFile.encodeName()

static PySide.QtCore.QFile.encodeName(fileName)
Parameters:fileName – unicode
Return type:PySide.QtCore.QByteArray

By default, this function converts fileName to the local 8-bit encoding determined by the user’s locale. This is sufficient for file names that the user chooses. File names hard-coded into the application should only use 7-bit ASCII filename characters.

See also

PySide.QtCore.QFile.decodeName() setEncodingFunction()

PySide.QtCore.QFile.error()
Return type:PySide.QtCore.QFile.FileError

Returns the file error status.

The I/O device status returns an error code. For example, if PySide.QtCore.QFile.open() returns false, or a read/write operation returns -1, this function can be called to find out the reason why the operation failed.

PySide.QtCore.QFile.exists()
Return type:PySide.QtCore.bool

This is an overloaded function.

Returns true if the file specified by PySide.QtCore.QFile.fileName() exists; otherwise returns false.

static PySide.QtCore.QFile.exists(fileName)
Parameters:fileName – unicode
Return type:PySide.QtCore.bool

Returns true if the file specified by fileName exists; otherwise returns false.

PySide.QtCore.QFile.fileEngine()
Return type:PySide.QtCore.QAbstractFileEngine

Returns the QIOEngine for this PySide.QtCore.QFile object.

PySide.QtCore.QFile.fileName()
Return type:unicode

Returns the name set by PySide.QtCore.QFile.setFileName() or to the PySide.QtCore.QFile constructors.

PySide.QtCore.QFile.flush()
Return type:PySide.QtCore.bool

Flushes any buffered data to the file. Returns true if successful; otherwise returns false.

PySide.QtCore.QFile.handle()
Return type:PySide.QtCore.int

Returns the file handle of the file.

This is a small positive integer, suitable for use with C library functions such as fdopen() and fcntl(). On systems that use file descriptors for sockets (i.e. Unix systems, but not Windows) the handle can be used with PySide.QtCore.QSocketNotifier as well.

If the file is not open, or there is an error, PySide.QtCore.QFile.handle() returns -1.

This function is not supported on Windows CE.

Parameters:
  • oldname – unicode
  • newName – unicode
Return type:

PySide.QtCore.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.

PySide.QtCore.QFile.link(newName)
Parameters:newName – unicode
Return type:PySide.QtCore.bool

Creates a link named linkName that points to the file currently specified by PySide.QtCore.QFile.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 PySide.QtCore.QFile.error() to return RenameError .

Note

To create a valid link on Windows, linkName must have a .lnk file extension.

Note

On Symbian, no link is created and false is returned if PySide.QtCore.QFile.fileName() currently specifies a directory.

PySide.QtCore.QFile.map(offset, size[, flags=NoOptions])
Parameters:
Return type:

PySide.QtCore.uchar

Maps size bytes of the file into memory starting at offset . A file should be open for a map to succeed but the file does not need to stay open after the memory has been mapped. When the PySide.QtCore.QFile is destroyed or a new file is opened with this object, any maps that have not been unmapped will automatically be unmapped.

Any mapping options can be passed through flags .

Returns a pointer to the memory or 0 if there is an error.

Note

On Windows CE 5.0 the file will be closed before mapping occurs.

PySide.QtCore.QFile.open(fd, flags)
Parameters:
  • fdPySide.QtCore.int
  • flagsPySide.QtCore.QIODevice.OpenMode
Return type:

PySide.QtCore.bool

static PySide.QtCore.QFile.permissions(filename)
Parameters:filename – unicode
Return type:PySide.QtCore.QFile.Permissions

This is an overloaded function.

Returns the complete OR-ed together combination of QFile.Permission for fileName .

PySide.QtCore.QFile.permissions()
Return type:PySide.QtCore.QFile.Permissions

Returns the complete OR-ed together combination of QFile.Permission for the file.

Parameters:fileName – unicode
Return type:unicode

Use PySide.QtCore.QFile.symLinkTarget() instead.

PySide.QtCore.QFile.readLink()
Return type:unicode

Use PySide.QtCore.QFile.symLinkTarget() instead.

PySide.QtCore.QFile.remove()
Return type:PySide.QtCore.bool

Removes the file specified by PySide.QtCore.QFile.fileName() . Returns true if successful; otherwise returns false.

The file is closed before it is removed.

static PySide.QtCore.QFile.remove(fileName)
Parameters:fileName – unicode
Return type:PySide.QtCore.bool

This is an overloaded function.

Removes the file specified by the fileName given.

Returns true if successful; otherwise returns false.

PySide.QtCore.QFile.rename(newName)
Parameters:newName – unicode
Return type:PySide.QtCore.bool

Renames the file currently specified by PySide.QtCore.QFile.fileName() to newName . Returns true if successful; otherwise returns false.

If a file with the name newName already exists, PySide.QtCore.QFile.rename() returns false (i.e., PySide.QtCore.QFile will not overwrite it).

The file is closed before it is renamed.

static PySide.QtCore.QFile.rename(oldName, newName)
Parameters:
  • oldName – unicode
  • newName – unicode
Return type:

PySide.QtCore.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, PySide.QtCore.QFile.rename() returns false (i.e., PySide.QtCore.QFile will not overwrite it).

static PySide.QtCore.QFile.resize(filename, sz)
Parameters:
  • filename – unicode
  • szPySide.QtCore.qint64
Return type:

PySide.QtCore.bool

This is an overloaded function.

Sets fileName to size (in bytes) sz . Returns true if the file 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.

PySide.QtCore.QFile.resize(sz)
Parameters:szPySide.QtCore.qint64
Return type:PySide.QtCore.bool

Sets the file size (in bytes) sz . Returns true if the file if the resize succeeds; false otherwise. If sz is larger than the file currently is the new bytes will be set to 0, if sz is smaller the file is simply truncated.

See also

PySide.QtCore.QFile.size() PySide.QtCore.QFile.setFileName()

PySide.QtCore.QFile.setFileName(name)
Parameters:name – unicode

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 :meth:`PySide.QtCore.QFile.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.

PySide.QtCore.QFile.setPermissions(permissionSpec)
Parameters:permissionSpecPySide.QtCore.QFile.Permissions
Return type:PySide.QtCore.bool
static PySide.QtCore.QFile.setPermissions(filename, permissionSpec)
Parameters:
  • filename – unicode
  • permissionSpecPySide.QtCore.QFile.Permissions
Return type:

PySide.QtCore.bool

PySide.QtCore.QFile.symLinkTarget()
Return type:unicode

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. QFile.exists() returns true if the symlink points to an existing file.

static PySide.QtCore.QFile.symLinkTarget(fileName)
Parameters:fileName – unicode
Return type:unicode

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 fileName does not correspond to a symbolic link.

This name may not represent an existing file; it is only a string. QFile.exists() returns true if the symlink points to an existing file.

PySide.QtCore.QFile.unmap(address)
Parameters:addressPySide.QtCore.uchar
Return type:PySide.QtCore.bool

Unmaps the memory address .

Returns true if the unmap succeeds; false otherwise.

PySide.QtCore.QFile.unsetError()

Sets the file’s error to QFile.NoError .