QFileInfo vs QFile to check if a file is writable

I use PyQt, and I noticed strange behavior when testing my application on Windows (everything works as expected on Linux).

I have a file that I can read and write, and I want to check it in the application:

>>> from PyQt4.QtCore import QFile, QFileInfo

>>> f1 = QFileInfo("C:\Users\Maxime\Desktop\script.py")
>>> f2 = QFile("C:\Users\Maxime\Desktop\script.py")

>>> f1.isWritable()
True
>>> f2.isWritable()
False

So it seems to be QFilewrong in this case. But in another read-only file:

>>> f1 = QFileInfo("C:\Program Files (x86)\MySoftware\stuff\script.py")
>>> f2 = QFile("C:\Program Files (x86)\MySoftware\stuff\script.py")

>>> f1.isWritable()
True
>>> f2.isWritable()
False

Now this QFileInfois what is wrong!

So, I decided that instead I should use os.access:

>>> import os

>>> os.access("C:\Users\Maxime\Desktop\script.py")
True
>>> os.access("C:\Program Files (x86)\MySoftware\stuff\script.py")
True

So, it is os.accessalso erroneous in one case and returns the same results as QFileInfo.

I have a few questions:

  • I am not familiar with Windows, is there something that I am missing?
  • Qt, QFileInfo QFile, , . ?
  • Qt ( Python?), , Linux Mac OS.

Edit:

, QFile:: isWritable() False, .

>>> f = QFile("C:\Users\Maxime\Desktop\script.py")
>>> f.open(QFile.WriteOnly)
True
>>> f.isWritable()
True

>>> f = QFile("C:\Program Files (x86)\MySoftware\stuff\script.py")
>>> f.open(QFile.WriteOnly)
False
>>> f.isWritable()
False
+4
1

, .

QFileInfo , . , refresh setCaching, .

, , QFile.isWritable False, . . , isWritable OpenMode . (QIODevice.NotOpen) , , QIODevice.ReadWrite, .

, , , , QFileInfo.isWritable, . QFileInfo.permission ( ). os.access os.stat.

, script, :

import os, stat, sip

sip.setapi('QString', 2)
from PyQt4.QtCore import QTemporaryFile, QFile, QFileInfo

tmp = QTemporaryFile()
tmp.setAutoRemove(False)
tmp.open()
tmp.close()

path = tmp.fileName()

info = QFileInfo(path)
print('File: %s' % info.filePath())
print('')
print('Qt Writable: %s' % info.isWritable())
print('Qt Permission: %s' % bool(info.permissions() & QFile.WriteUser))
print('Py Writable: %s' % os.access(path, os.W_OK))
print('Py Permission: %s' % bool(os.stat(path).st_mode & stat.S_IWUSR))

tmp = QFile(path)
tmp.setPermissions(QFile.ReadUser)
print('')
print('Set Permissions: ReadUser')
print('')

info.refresh()
print('Qt Writable: %s' % info.isWritable())
print('Qt Permission: %s' % bool(info.permissions() & QFile.WriteUser))
print('Py Writable: %s' % os.access(path, os.W_OK))
print('Py Permission: %s' % bool(os.stat(path).st_mode & stat.S_IWUSR))

tmp.setPermissions(QFile.WriteUser)
print('')
print('Removed: %s' % tmp.remove())

, Linux, WinXp, :

File: /tmp/qt_temp.TJ1535

Qt Writable: True
Qt Permission: True
Py Writable: True
Py Permission: True

Set Permissions: ReadUser

Qt Writable: False
Qt Permission: False
Py Writable: False
Py Permission: False

Removed: True
+2

All Articles