6

Why "\" and "/" are mixed?

os.getcwd() emits backslash string.

On the other hand, QFileDialog emits forward slash string.

Why?

Example

Please execute this sample code.

from PySide import QtGui
from PySide import QtCore
import sys
import os

class DirectoryPrinter(QtGui.QWidget):
    def __init__(self,parent=None):
        super(DirectoryPrinter,self).__init__(parent=None)

        self.filedialog_pushbutton = QtGui.QPushButton("filedialog",self)
        self.connect(self.filedialog_pushbutton,QtCore.SIGNAL("clicked()"),self.filename_getter)

    def filename_getter(self):
        print("from os.getcwd()",os.getcwd())
        filename = QtGui.QFileDialog.getOpenFileName(self,"Select your file",os.path.expanduser("~"))[0]
        print("from QFileDialog",filename)


def main():
    try:
        QtGui.QApplication([])
    except Exception as e:
        print(22,e)
    directoryprinter = DirectoryPrinter()
    directoryprinter.show()

    sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
    main()

Result (on my occasion)

from os.getcwd(): J:\

from QFileDialog: C:/Users/******/setup.py

jpeg
  • 2,372
  • 4
  • 18
  • 31
Haru
  • 1,884
  • 2
  • 12
  • 30

2 Answers2

7

This is because QFileDialog uses forward slashes regardless of OS. This makes it easier to write path handling code.

You can use os.path.normpath to converts forward slashes to backward slashes in a path on Windows.

jpeg
  • 2,372
  • 4
  • 18
  • 31
  • 1
    In fact , I have found out this result from PySide Documentation,QDir class.But your information has great amount of knowledge and very useful.thanks. – Haru Aug 22 '18 at 06:38
2

This is a design decision on Qt's part, while Python uses the system's conventions for paths*.

If you want to convert by using Qt itself, you can use:

QtCore.QDir.toNativeSeparators(filename)

*Note: Python uses the system's conventions, some functions handle forward slashes on Windows. If you're building your own paths in Python, I suggest you take a look at Pathlib, which is in Python's standard library.

**Tip: If building with pathlib, the simplest option is to not use Path.joinpath() when joining the directory with the filename. Use slashes as operators instead:

from pathlib import Path
dirpath = Path(r'Avoid\Using\Hardcoded\Paths')
filename = dirpath / "basename.ext"
Ronan Paixão
  • 8,297
  • 1
  • 31
  • 27