I'm writing a small Python code to join text files, and the files are selected as an user input. But it's important that I get the order of the users selection, as I want to join the files in the selected order. But I see that the list returned by getOpenFileNames does not preserve the selection order.
Does anybody have any suggestion to capture the selection order?
Thank you.
I originally wanted to suggest writing a callback for the currentChanged signal that tracks the selection, but it seems like this signal doesn't get called when using getOpenFileNames. An alternative would be displaying the dialog with show() and connecting a callback to filesSelected, which is called after the user clicks the "open" button on the dialog. The argument to the callback is a list with the selected files which seems to be in the order of their selection (just tested it on python3/pyqt4).
def callback(files):
joined_files = ''.join([open(f).read() for f in files])
do_something_with(joined_files)
dialog = QtGui.QFileDialog()
dialog.setFileMode(3) #allow selection of multiple files
dialog.filesSelected.connect(callback)
dialog.show()
One problem with this is that the order isn't indicated to the user in an easy way - the "file" textbox contains the ordered files' names, but this is messy when you select more than a few files. A better but slightly more complicated approach would be building a widget or dialog with a FileDialog for selecting files and a List/TableWidget holding the files to process, where the user could add Files one at a time. This would allow for a better overwiew as well as easy selection of files from multiple directories and better extendability (e.g. filtering, rearranging, sorting the selection).
self.filename = QtGui.QFileDialog.getOpenFileNames(
self,
"Cargar tu documento",
self.lastOpenedFile,
"*.doc;*.odt;*.pdf" )
Related
I am trying to create a way using pywinauto to select multiple files in Win Explorer.
The below code works great to select/get one file, but I am stuck on using the same approach to select multiple files.
The code is part of a method which takes a passed path, then splits the path string to get the filename. I use get_item(filename) to select the file. The last step is a right-click on the file.
if os.path.isdir(fso_to_select):
item_to_select = fso_to_select.split("\\")[-1]
self.__explorer_win = self.__application.Window_(top_level_only=True, active_only=True,
class_name='CabinetWClass')
self.__explorer_win.set_focus().maximize()
fso_item = self.__explorer_win.ItemsView.get_item(item_to_select)
fso_item.right_click_input()
I am trying to use the browse function in PySimpleGUI. I have used PySimpleGUI file browser specific file type to find out how to browse. However there are two file types that I want to choose from and multiple files need to be selected for this to work. My question:
How do you use the browse function for browsing two types of files? and also How do you allow multiple files to be browsed? and finally How do you tell each file apart?
I know that there is a key function for getting data but how can I do that for more than one file.
In case you are a tiny bit confused:
The user must select the browse function and must be able to choose from .txt and .Docx files while selecting more than one file. The program must be able to tell the difference between the files so a function can be run on each file separately.
My code so far:
import PySimpleGUI as sg
sg.theme('DarkAmber') # Add a touch of color
# All the stuff inside your window.
layout = [ [sg.FileBrowse(file_types=(("Text Files", "*.txt"),))],
[sg.Button('Lets GO!!!')]
]
# Create the Window
window = sg.Window('Test', layout).Finalize()
window.Maximize()
Can someone finish this code?
According to the documentation:
file_types=(("Text Files", "*.txt"),("CSV Files", "*.csv"),)
works.
I have a GUI with a tool button next to a Combobox. The tool button opens a directory browser to select a file and then adds that file Name to the Combobox drop-down list.
def showFileOpenDialogLoad(self):
""" Opens dialog to get Load file path """
filename = QFileDialog.getOpenFileName(self, 'Open file',
'/home')
self.comboBoxFilePathLoad.addItem(filename)
This works perfectly, however, I then want the Combobox to directly display the last added filename. I have tried using .insertItem(0,filename)instead and then setting self.comboBoxFilePathLoad.currentIndex = -1but it still displays the first added filename even though in the Dropdown list the last added filename is now above the old and displayed one. Apparently in C# you would use cmbBox.SelectedIndex = cmbBox.Items.count -1 but Pyqt does not have a SelectedIndexmethod.
This does not seem like such a difficult question but somehow I can not find a solution to it online... The QComboBox Class Reference does not explain count and CurrentIndex either. Thank you for your help!
I am using static method:
path = QtGui.QFileDialog.getSaveFileName(self, SAVE_TO_STR, NAME_STR, 'CSV(*.csv)')
where I get path as full_path\some_name.csv
but I need to set different language to buttons and labels of dialog, so I've been looking at docs and find out that I can't do that with static method and I've come up with this code:
ddd = QtGui.QFileDialog(self, SAVE_TO_IN_OTHER_LANGUAGE_STR, NAME_STR, 'CSV(*.csv)')
ddd.setAcceptMode (QtGui.QFileDialog.AcceptSave)
ddd.setLabelText( QtGui.QFileDialog.Accept, "Save - in other language" )
ddd.setLabelText( QtGui.QFileDialog.Reject, "Cancel - in other language" )
ddd.setLabelText( QtGui.QFileDialog.LookIn, "Look in - in other language" )
if ddd.exec_():
path = QtCore.QString(ddd.selectedFiles()[0])
I am trying to set it to look like first one so my questions are:
path I get is ok, but missing .csv at the end, so it saves file with no extension.
should I manually add .csv at the end of the path?
when I choosing where to save and click on folder, "save" button turns to "open". How to change that button text to "Open" in other language?
folders list at the left side of dialog is not complex as when I use QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and User, instead of modern tree with favorites and partitions under My Computer.
1) path I get is ok, but missing .csv at the end, so it saves file with
no extension. should I manually add .csv at the end of the path?
Answer: I think you shouldn't manually add .csv at the end of the path. In PyQt API have this solution to solve it, use QFileDialog.setDefaultSuffix (self, QString suffix);
pathQFileDialog = QtGui.QFileDialog(self)
pathQFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
pathQFileDialog.setNameFilter('CSV(*.csv)')
pathQFileDialog.setDefaultSuffix('csv')
Reference: http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#setDefaultSuffix
2) when I choosing where to save and click on folder, "save" button
turns to "open". How to change that button text to "Open" in other
language?
Answer: My opinion of PyQt, No. In Qt (C++) at file qfiledialog.cpp I found your problem in method void QFileDialogPrivate::_q_updateOkButton() at line between 2886 and 2888. It force "&Open" label;
button->setEnabled(enableButton);
if (acceptMode == QFileDialog::AcceptSave)
button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel);
Reference: https://qt.gitorious.org/qt/qt/source/57756e72adf2081137b97f0e689dd16c770d10b1:src/gui/dialogs/qfiledialog.cpp#L2796-2888
3) folders list at the left side of dialog is not complex as when I use
QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and
User, instead of modern tree with favorites and partitions under My
Computer.
Answer: Because on Windows, Mac OS X and Symbian^3, this static function (QtGui.QFileDialog.getSaveFileName()) will use the native file dialog and not a QFileDialog.
Reference: pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#getSaveFileName
Regards,
I'm working on a python program that will automatically combine sets of files based on their names.
Being a newbie, I wasn't quite sure how to go about it, so I decided to just brute force it with the win32api.
So I'm attempting to do everything with virtual keys. So I run the script, it selects the top file (after arranging the by name), then sends a right click command,selects 'combine as adobe PDF', and then have it push enter. This launched the Acrobat combine window, where I send another 'enter' command. The here's where I hit the problem.
The folder where I'm converting these things loses focus and I'm unsure how to get it back. Sending alt+tab commands seems somewhat unreliable. It sometimes switches to the wrong thing.
A much bigger issue for me.. Different combination of files take different times to combine. though I haven't gotten this far in my code, my plan was to set some arbitrarily long time.sleep() command before it finally sent the last "enter" command to finish and confirm the file name completing the combination process. Is there a way to monitor another programs progress? Is there a way to have python not execute anymore code until something else has finished?
I would suggest using a command-line tool like pdftk http://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/ - it does exactly what you want, it's cross-platform, it's free, and it's a small download.
You can easily call it from python with (for example) subprocess.Popen
Edit: sample code as below:
import subprocess
import os
def combine_pdfs(infiles, outfile, basedir=''):
"""
Accept a list of pdf filenames,
merge the files,
save the result as outfile
#param infiles: list of string, names of PDF files to combine
#param outfile: string, name of merged PDF file to create
#param basedir: string, base directory for PDFs (if filenames are not absolute)
"""
# From the pdftk documentation:
# Merge Two or More PDFs into a New Document:
# pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf
if basedir:
infiles = [os.path.join(basedir,i) for i in infiles]
outfile = [os.path.join(basedir,outfile)]
pdftk = [r'C:\Program Files (x86)\Pdftk\pdftk.exe'] # or wherever you installed it
op = ['cat']
outcmd = ['output']
args = pdftk + infiles + op + outcmd + outfile
res = subprocess.call(args)
combine_pdfs(
['p1.pdf', 'p2.pdf'],
'p_total.pdf',
'C:\\Users\\Me\\Downloads'
)