Home python File selection and / or QFileDialog

File selection and / or QFileDialog

Author

Date

Category

How can I put on the button to select or file or folder.
There are options:
qtwidgets.qfiledialog.getexistingDirectory and qtwidgets.qfiledialog.getopenfilename ()

And how to make it possible to choose or folder, or file?
And I would also like to know if it is possible when using qtwidgets.QFileDialog.getOpenFileName () to make only a specific extension files

front.py

# - * - Coding: UTF-8 - * -
# Form Implementation Generated From Reading UI File 'Front.ui'
#
# Created by: Pyqt5 UI Code Generator 5.14.2
#
# Warning! All Changes Made In This File Will Be Lost!
From Pyqt5 Import Qtcore, Qtgui, Qtwidgets
Class UI_MainWindow (Object):
  DEF SETUPUI (Self, Mainwindow):
    MainWindow.SetObjectName ("Mainwindow")
    MainWindow.Resize (300, 400)
    Mainwindow.setminimumsize (qtcore.qsize (300, 400))
    Mainwindow.setmaximumsize (qtcore.qsize (300, 400))
    self.centralwidget = qtwidgets.qwidget (Mainwindow)
    self.centralwidget.setObjectName ("CentralWidget")
    self.btnbrowse = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnbrowse.setgeometry (qtcore.qrect (0, 0, 131, 23))
    self.btnbrowse.setobjectName ("btnbrowse")
    self.listwidget = qtwidgets.QlistWidget (self.centralwidget)
    self.listwidget.setgeometry (qtcore.qrect (0, 20, 131, 151))
    self.listwidget.setObjectName ("ListWidget")
    self.btnarch = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnarch.setgeometry (qtcore.qrect (110, 180, 81, 23))
    self.btnarch.setObjectName ("Btnarch")
    Self.ExtractButton = qtwidgets.qpushbutton (self.centralwidget)
    Self.ExtractButton.Setgeometry (Qtcore.Qrect (180, 0, 81, 23))
    Self.ExtractButton.SetObjectName ("ExtractButton")
    Mainwindow.SetCentralWidget (self.centralwidget)
    Self.Menubar = Qtwidgets.QMenubar (Mainwindow)
    self.umenubar.setgeometry (qtcore.qrect (0, 0, 300, 21))
    Self.Menubar.SetObjectName ("Menubar")
    Mainwindow.Setmenubar (Self.Menubar)
    self.statusbar = qtwidgets.Qstatusbar (Mainwindow)
    self.statusbar.setObjectName ("Statusbar")
    Mainwindow.Setstatusbar (Self.statusbar)
    Self.Retranslateui (Mainwindow)
    Qtcore.QMetaObject.ConnectslotsByname (Mainwindow)
  Def Retranslateui (Self, Mainwindow):
    _Translate = Qtcore.QcoreApplication.translate.
    Mainwindow.setwindowtle (_Translate ("Mainwindow", "Mainwindow"))
    self.btnbrowse.settext (_Translate ("Mainwindow", "Select Folder"))
    self.btnarch.settext (_Translate ("Mainwindow", "Archive"))
    self.extractButton.settext (_Translate ("Mainwindow", "Extract"))

main.py

import frie
Import SYS, OS, ZIPFILE, TRACEBACK
from pyqt5 import qtwidgets
Class exampleApp (qtwidgets.qmainwindow, front.ui_mainwindow):
  Directory = ''
  Def __init __ (Self):
    # It is necessary to access variables, methods
    # etc. in the Design.py file
    Super () .__ init __ ()
    Self.Setupui (Self) # It is necessary to initialize design
    self.btnbrowse.clicalked.connect (Self.Browse_Folder)
    self.btnarch.clicked.connect (Self.arch_folder)
    self.extractButton.clicalked.connect (Self.Extract)
  DEF BROWSE_Folder (Self):
    self.listwidget.clear () # in case there are already elements in the list
    self.directory = qtwidgets.QFileDialog.getexistingDirectory (Self, "Select Folder")
    If self.directory: # Do not continue execution if the user has not selected the directory
      for file_name in os.listdir (self.directory): # for each file in the directory
        self.listwidget.additem (File_Name) # Add file to listwidget
    Return Self.directory.
  Def Arch_Folder (Self):
    Archive = zipfile.zipfile ('Test.zip', 'W')
    Dirfiles = OS.ListDir (Self.directory)
    File in dirfiles:
      Try: 
Archive.write (self.directory + "/" + file, compress_type = zipfile.zip_deflated)
      Except:
        Print (traceback.format_exc ())
    Archive.Close ()
  DEF EXTRACT (SELF):
    Self.Archive = qtwidgets.QFileDialog.getOpenFileName (Self, "Select Archive")
    zip_arch = zipfile.zipfile (Self.Archive [0], 'R')
    FOR FILES IN ZIP_ARCH.NAMELIST ():
      ZIP_ARCH.EXTRACT (Files)
    zip_arch.close ()
DEF Main ():
  App = Qtwidgets.Qapplication (SYS.Argv) # New Qapplication instance
  Window = ExampleApp () # Create an Exampleapp object object
  Window.Show () # Show window
  app.exec_ () # and launch the application
if __name__ == '__main__': # If you start the file directly, and do not import
  Main () # then run the Main () function

Answer 1, Authority 100%

Try this:

import sys
Import OS.
Import zipfile
Import Traceback
From Pyqt5 Import Qtcore, Qtgui, Qtwidgets
#Import Front
Class UI_MainWindow (Object):
  DEF SETUPUI (Self, Mainwindow):
    MainWindow.SetObjectName ("Mainwindow")
    MainWindow.Resize (300, 400)
    Mainwindow.SetminimumSize (Qtcore.Qsize (500, 400))
# Mainwindow.Setmaximumsize (qtcore.Qsize (300, 400))
    self.centralwidget = qtwidgets.qwidget (Mainwindow)
    self.centralwidget.setObjectName ("CentralWidget")
    self.btnbrowse = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnbrowse.setgeometry (qtcore.qrect (0, 0, 131, 23))
    self.btnbrowse.setobjectName ("btnbrowse")
    self.listwidget = qtwidgets.QlistWidget (self.centralwidget)
    self.listwidget.setgeometry (qtcore.qrect (0, 20, 331, 151))
    self.listwidget.setObjectName ("ListWidget")
    self.btnarch = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnarch.setgeometry (qtcore.qrect (110, 180, 81, 23))
    self.btnarch.setObjectName ("Btnarch")
    Self.ExtractButton = qtwidgets.qpushbutton (self.centralwidget)
    Self.ExtractButton.Setgeometry (Qtcore.Qrect (380, 0, 81, 23))
    Self.ExtractButton.SetObjectName ("ExtractButton")
    Mainwindow.SetCentralWidget (self.centralwidget)
    Self.Menubar = Qtwidgets.QMenubar (Mainwindow)
    self.umenubar.setgeometry (qtcore.qrect (0, 0, 300, 21))
    Self.Menubar.SetObjectName ("Menubar")
    Mainwindow.Setmenubar (Self.Menubar)
    self.statusbar = qtwidgets.Qstatusbar (Mainwindow)
    self.statusbar.setObjectName ("Statusbar")
    Mainwindow.Setstatusbar (Self.statusbar)
    Self.Retranslateui (Mainwindow)
    Qtcore.QMetaObject.ConnectslotsByname (Mainwindow)
  Def Retranslateui (Self, Mainwindow):
    _Translate = Qtcore.QcoreApplication.translate.
    Mainwindow.setwindowtle (_Translate ("Mainwindow", "Mainwindow"))
    self.btnbrowse.settext (_Translate ("Mainwindow", "Choose ..."))
    self.btnarch.settext (_Translate ("Mainwindow", "Archive"))
    self.extractButton.settext (_Translate ("Mainwindow", "Extract"))
Class Dialog (qtwidgets.qdialog): # +++
  Def __init __ (Self, Parent = None):
    Super (Dialog, Self) .__ Init __ (Parent)
    label = qtwidgets.QLabel ("Make a choice:")
    self.rbdir = qtwidgets.qradioButton ('Directory', Self)
    self.rbpath = qtwidgets.qradioButton ('Pathfile', Self)
    btnok = qtwidgets.qpushbutton ("OK", clicked = self.hide)
    layout = qtwidgets.qgridlayout (SELF)
    layout.addwidget (label, 0, 0, 1, 3)
    layout.addwidget (Self.rbdir, 1, 1, 1, 1)
    layout.addwidget (Self.rbpath, 2, 1, 1, 1)
    layout.addwidget (Btnok, 3, 2, 1, 1)
#Class Exampleapp (qtwidgets.qmainwindow, front.ui_mainwindow):
Class exampleApp (qtwidgets.qmainwindow, ui_mainwindow):
  Directory = ''
  Pathfile = '' # +++
  Def __init __ (Self):
    # It is necessary to access variables, methods
    # etc. in the Design.py file
    Super () .__ init __ ()
    Self.Setupui (Self) # It is necessary to initialize design 
self.btnBrowse.clicked.connect (self.browse_folder)
    self.btnArch.clicked.connect (self.arch_folder)
    self.extractButton.clicked.connect (self.extract)
    self.dialog = Dialog () # +++
# ++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  def browse_folder (self):
    self.directory, self.pathFile = '', ''
    self.dialog.exec_ ()
    if self.dialog.rbDir.isChecked ():
      print (f'dialog ')
      self.listWidget.clear () # In case there are already elements in the list
      self.directory = QtWidgets.QFileDialog.getExistingDirectory (self, "Select folder")
      if self.directory: # do not continue execution if the user has not selected a directory
        for file_name in os.listdir (self.directory): # for each file in the directory
          self.listWidget.addItem (file_name) # add file to listWidget
    elif self.dialog.rbPath.isChecked ():
      print (f'rbPath ')
      self.pathFile, _ = QtWidgets.QFileDialog.getOpenFileName (
                        self,
                        'Open File', './',
                        'Files (* .py * .txt * .log)')
      if self.pathFile:
        self.listWidget.addItem (self.pathFile) # add file to listWidget
    else:
      print (f'no ')
      msg = QtWidgets.QMessageBox.information (self, 'Message', 'You haven't selected anything.')
# ++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  def arch_folder (self):
    print (f'def arch_folder (self): directory = `{self.directory}` ')
    print (f'def arch_folder (self): pathFile = `{self.pathFile}` ')
    '' '
    archive = zipfile.ZipFile ('test.zip', 'w')
    dirfiles = os.listdir (self.directory)
    for file in dirfiles:
      try:
        archive.write (self.directory + "/" + file, compress_type = zipfile.ZIP_DEFLATED)
      except:
        print (traceback.format_exc ())
    archive.close ()
    '' '
  def extract (self):
    print (f'def extract (self): directory = `{self.directory}` ')
    print (f'def extract (self): pathFile = `{self.pathFile}` ')
    '' '
    self.archive = QtWidgets.QFileDialog.getOpenFileName (self, "Select archive")
    zip_arch = zipfile.ZipFile (self.archive [0], 'r')
    for files in zip_arch.namelist ():
      zip_arch.extract (files)
    zip_arch.close ()
    '' '
def main ():
  app = QtWidgets.QApplication (sys.argv) # New QApplication instance
  window = ExampleApp () # Create an Object of the ExampleApp class
  window.show () # Show the window
  app.exec_ () # and run the application
if __name__ == '__main__': # If we run the file directly instead of importing
  main () # then run the main () function


Answer 2

So that I click on the conditional “select”, the file selection window opens immediately,
but in it I could select both file and folder . Is it possible?

QFileDialog doesn’t allow this natively.
The only solution is to create your own getOpenFilesAndDirs .

Note that you cannot use your OS’s own dialogs to achieve this, since Qt has almost no control over them,
this is the reason for the dialog.DontUseNativeDialog flag, which is required.

The following code works the same as static methods ,
and returns the selected items (or none if the dialog is canceled).

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow (object):
  def setupUi (self, MainWindow):
    MainWindow.setObjectName ("MainWindow")
    MainWindow.resize (300, 400) 
Mainwindow.SetminimumSize (Qtcore.Qsize (500, 400))
    self.centralwidget = qtwidgets.qwidget (Mainwindow)
    self.centralwidget.setObjectName ("CentralWidget")
    self.btnbrowse = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnbrowse.setgeometry (qtcore.qrect (0, 0, 131, 23))
    self.btnbrowse.setobjectName ("btnbrowse")
    self.listwidget = qtwidgets.QlistWidget (self.centralwidget)
    self.listwidget.setgeometry (qtcore.qrect (0, 20, 331, 151))
    self.listwidget.setObjectName ("ListWidget")
    self.btnarch = qtwidgets.qpushbutton (Self.centralWidget)
    self.btnarch.setgeometry (qtcore.qrect (110, 180, 81, 23))
    self.btnarch.setObjectName ("Btnarch")
    Self.ExtractButton = qtwidgets.qpushbutton (self.centralwidget)
    Self.ExtractButton.Setgeometry (Qtcore.Qrect (380, 0, 81, 23))
    Self.ExtractButton.SetObjectName ("ExtractButton")
    Mainwindow.SetCentralWidget (self.centralwidget)
    Self.Menubar = Qtwidgets.QMenubar (Mainwindow)
    self.umenubar.setgeometry (qtcore.qrect (0, 0, 300, 21))
    Self.Menubar.SetObjectName ("Menubar")
    Mainwindow.Setmenubar (Self.Menubar)
    self.statusbar = qtwidgets.Qstatusbar (Mainwindow)
    self.statusbar.setObjectName ("Statusbar")
    Mainwindow.Setstatusbar (Self.statusbar)
    Self.Retranslateui (Mainwindow)
    Qtcore.QMetaObject.ConnectslotsByname (Mainwindow)
  Def Retranslateui (Self, Mainwindow):
    _Translate = Qtcore.QcoreApplication.translate.
    Mainwindow.setwindowtle (_Translate ("Mainwindow", "Mainwindow"))
    self.btnbrowse.settext (_Translate ("Mainwindow", "Choose ..."))
    self.btnarch.settext (_Translate ("Mainwindow", "Archive"))
    self.extractButton.settext (_Translate ("Mainwindow", "Extract"))
DEF GetOpenFilesAndDirs (Parent = None, Caption = '', Directory = '',
            Filter = '', initialFilter = '', options = none):
  Def UpdateText ():
    # update the contents of the string editing widget selected files
    SELECTED = []
    For index in view.selectionmodel (). selectedrows ():
      selected.append ('"{}". Format (index.data ()))
    layedit.settext ('' .join (selected))
  Dialog = Qtwidgets.QFileDialog (Parent, WindowTitle = Caption)
  dialog.setfilemode (dialog.existingfiles)
  If Options:
    Dialog.Setoptions (Options)
  Dialog.Setoption (Dialog.dontusenativeDialog, True) # !!!
  If Directory:
    Dialog.SetDirectory (Directory)
  IF Filter:
    Dialog.SetNameFilter (Filter)
    IF InitialFilter:
      Dialog.SelectNameFilter (InitialFilter)
  # Default if the directory is open in the file list mode,
  # Qfiledialog.accept () shows the contents of this catalog,
  # But we need to have the ability to "open" and directories, how can we do with files,
  # So we just override `accept ()` with the default QDialog implementation,
  # which will just return `dialog.selectedfiles ()`
  dialog.accept = lambda: qtwidgets.qdialog.accept (dialog)
  # In a non-dialogue there are many ideas of elements,
  # But those that displays actual content are created inside qstackedwidget;
  # This QtreeView and QlistView, and the tree is used only then
  # When viewmode is set to qfiledialog.details, which is not in this case.
  stackedwidget = dialog.findchild (qtwidgets.qstackedwidget)
  View = stackedwidget.findchild (qtwidgets.qlistview)
  View.SelectionModel (). SelectionChanged.connect (UpdateText)
  layedit = dialog.findchild (qtwidgets.qlineedit)
  # Clean the contents of the edit line whenever the current directory changes
  dialog.directoryentered.connect (lambda: lineedit.settext (''))
  dialog.exec_ ()
  Return dialog.selectedFiles ()
Class exampleApp (qtwidgets.qmainwindow, ui_mainwindow):
  Def __init __ (Self):
    Super () .__ init __ ()
    Self.Setupui (SELF)
    self.btnbrowse.clicalked.connect (Self.Browse_Folder)
    self.btnarch.clicked.connect (Self.arch_folder)
    self.extractButton.clicalked.connect (Self.Extract)
  DEF BROWSE_Folder (Self):
    selected_files = getopenfilesanddirs () 
Print (Selected_Files)
     If selected_files:
       self.listwidget.additems (selected_files)
     ELSE:
       msg = qtwidgets.qmessagebox.information (Self, 'Message', 'You have not chosen anything.')
   Def Arch_Folder (Self):
     Print (Flink Archiving: ... ')
   DEF EXTRACT (SELF):
     Print (F'Tho remove: ... ')
if __name__ == '__main__':
   App = Qtwidgets.Qapplication (SYS.Argv)
   Window = ExampleApp ()
   Window.Show ()
   sys.exit (app.exec_ ())

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions