Showing posts with label Open folder. Show all posts
Showing posts with label Open folder. Show all posts

Wednesday, February 3, 2016

Good and Pythonic way to iterate over files in a folder



First, we get the path by some way, most of cases with an open folder dialog.

Then we make a list with all files in that folder.

This can be useful for batch analyze / read/ write files.


import os


path = 'c://temp'
onlyfiles = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))]

Monday, November 23, 2015

Asking for User Input

In QGIS python (PyQGIS), the python comman raw_input() does not work as expected. And it will be not very practical to enter any input in Python Console.

One good alternative is to use "Qdialog". It is a module of PyQt (PyQt4.QtGui) library.
It can show a window asking for input, or asking to choose a file or folder.

We have to import it:

from PyQt4.QtGui import QFileDialog, QInputDialog, QMessageBox

QfileDialog - Window to select files or folders. It can be getOpenFileName - for opening files, getSaveFileName, for saving files, getExistingDirectory to select a folder. Example code for these types is shown below.

fileOpen = QFileDialog.getOpenFileName(None,'Select File:', 'c:/' , '.xls (*.xls)')

saveFileName = QtGui.QFileDialog.getSaveFileName(self, 'Dialog Title', '/path/to/default/directory', selectedFilter='*.txt')

folderSel = QFileDialog.getExistingDirectory(None,"Select Folder: ", 'c:/')


QInputDialog - customizable window. An example is shown below, showing a function that calls a customizable input window with defined width and height:

def windowSize(title, question, widthW, heightW):
    winD = QInputDialog(iface.mainWindow())
    winD.setInputMode(QInputDialog.TextInput)
    winD.setWindowTitle(title);
    winD.setLabelText(question)
    winD.resize(widthW,heightW)
    ok = winD.exec_()
    textInput = winD.textValue()
    return textInput

QMessageBox - It shows only a MessageBox With some information you want. Example:

QMessageBox.information(iface.mainWindow(), "Title", "Message")