Selecting Files (The Easy & Cool Way)
Hello World.
As I keep working on my Tool Development skills, I get very excited about libraries and techniques that not only make my life easier, but makes the user’s experience of using my tools a bit more enjoyable.
Some of the tools that I’ve developed, like the PDF Text Extractor & Wordlister, would ask the user to type in the file name. Which thing bring up the woes of having the user type in the name of the file in a specific way, like having to type “.txt” or “.pdf” extension, in order for Python to select the file.
If I hard-code the extension, then I would have to rely on the user NOT putting in the extension, other-wise it may not find the file, or even crash the program in some occasions. This was frustrating the crap out of me, so I needed a better solution.
// The Solution
The EasyGUI library.
This totally blew my mind, with this library, when the time comes for a file to be chosen, it will open up a window for the user to navigate simply select the file. Excellent.
Once it does that, of course in your terminal you will see the full path of the file, which I didn’t like, but there is a solution for that, and its by using one of the attributes of The OS library that is already pre-installed with Python.
// The Code
First, install EasyGUI.pip install easy-gui
Then you import EasyGUI & OS.import easygui
import os
This is the code for file selection, and to clean up the result. To only print the name of the file on the screen, not the whole path.
# popup window for the user to just select the file.
file = easygui.fileopenbox()# gives you just the name of the file, without the full path.
os.path.basename( file )
Now when ever you call “file”, it will pop a window for the user to choose the file of their choice.
This has really made my tools better, because now neither I nor the user would have to worry about typing in the EXACT file name and extension to get the result needed.
// Your Done
That’s it, its only a few lines of code, but it made a world of difference.
I hope this post has given you some ideas.
This has been ryn0f1sh, The PyNoob.
[R/F] End Of Line.