QFileDialog返回带有错误分隔符的选定文件



我注意到QFileDialog实例正在返回成员函数selectedFile()的绝对路径,该函数对于给定的操作系统具有错误的分隔符。这在跨平台语言(python)上是不被期望的

我应该做些什么来纠正这个问题,以便我的其余正确的独立于操作系统的python代码使用'os. exe '。Sep可能是正确的?我不想要记住什么地方可以用,什么地方不可以用。

您使用os.path.abspath函数:

>>> import os
>>> os.path.abspath('C:/foo/bar')
'C:\foo\bar'

答案来自另一个线程(这里),提到我需要使用QDir.toNativeSeparators()

所以我在我的循环中做了以下操作(这可能应该在pyqt中为我们完成):

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

最新更新