Apr-22-2017, 02:14 PM
I'm relatively new to python, just a couple of months into learning, but I wanted to share this, because I thought it was wickedly cool.
I had a problem today and thought it was a good chance to practice some python.
I want to make sure all the photos on my PC are backed up online, so I wanted to write a script just to find all directories on my external hard drive that contain pictures (just jpegs).
I come from a C++ background, so I started writing for loops to iterate the directories and files, but I thought, "there's got to be a better way."
I started searching and testing some code, and I whittled it down to just 5 lines of actual code, and only 1 of those is doing any real work!
It was just cool to see how powerful the language is, and I know this is just a simple task for python.
Here's what I ended up with:
The script file is located in the root directory of my external hard drive so that __file__ would just work.
Still learning, so please comment if there are better or more "pythonic" ways to do this.
I had a problem today and thought it was a good chance to practice some python.
I want to make sure all the photos on my PC are backed up online, so I wanted to write a script just to find all directories on my external hard drive that contain pictures (just jpegs).
I come from a C++ background, so I started writing for loops to iterate the directories and files, but I thought, "there's got to be a better way."
I started searching and testing some code, and I whittled it down to just 5 lines of actual code, and only 1 of those is doing any real work!
It was just cool to see how powerful the language is, and I know this is just a simple task for python.
Here's what I ended up with:
1 2 3 4 5 6 7 8 |
import os cur_dir = os.path.dirname(os.path.realpath(__file__)) dirs_with_pics = [root for root, dirs, files in os.walk(cur_dir) if any ( map ( lambda f: f.endswith( ".jpg" ), files))] for dir in dirs_with_pics: print ( dir ) |
Still learning, so please comment if there are better or more "pythonic" ways to do this.