1

I noticed that QFileDialog instance is returning absolute paths for the member function selectedFile() that have the wrong separator for the given operating system. This is not expected on a cross platform language (python)

What should I do to correct this so that the rest of my properly OS-independant python code using 'os.sep' can be correct? I don't want to have to remember where I can and can't use it.

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
  • There's almost never any reason to use os.sep. Forward slashes are portable everywhere, and using os.sep just leads to messy code, not greater portability. – Glenn Maynard May 14 '16 at 09:50

2 Answers2

2

You use the os.path.abspath function:

>>> import os
>>> os.path.abspath('C:/foo/bar')
'C:\\foo\\bar'
Blender
  • 289,723
  • 53
  • 439
  • 496
  • That also works. Interesting to see that str.split(os.sep) works as expected on that string. But I think that's because after assignment or operation the doubled backslash is removed. – UpAndAdam May 13 '13 at 14:23
  • @UpAndAdam: There is no double backslash. ```\\``` just what ```\``` looks like when you pass it through `repr`. – Blender May 13 '13 at 15:28
1

The answer came from another thread ( HERE ) that mentioned I need to use QDir.toNativeSeparators()

so I did the following in my loop (which should probably be done in pyqt itself for us):

def get_files_to_add(some_directory):
  addq = QFileDialog()
  addq.setFileMode(QFileDialog.ExistingFiles)
  addq.setDirectory(some_directory)
  addq.setFilter(QDir.Files)
  addq.setAcceptMode(QFileDialog.AcceptOpen)
  new_files = list()
  if addq.exec_() == QDialog.Accepted:
    for horrible_name in addq.selectedFiles():
      ### CONVERSION HERE ###
      temp = str(QDir.toNativeSeparators(horrible_name)
      ### 
      # temp is now as the os module expects it to be
      # let's strip off the path and the extension
      no_path = temp.rsplit(os.sep,1)[1]
      no_ext = no_path.split(".")[0]
      #... do some magic with the file name that has had path stripped and extension stripped
      new_files.append(no_ext)
      pass
    pass
  else:
    #not loading  anything
    pass
  return new_files
Community
  • 1
  • 1
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
  • 1
    I'd be interested to hear from the downvoter what is so wrong with this answer that merits a down vote. Especially since it solved my problem. – UpAndAdam May 13 '13 at 19:12