1

Looking to make some use out of Python! I wanted to write a script to move all those carelessly placed .jpg files from my desktop.

Thing, is the script I'm using doesn't seem to be finding anything.

thoughts?

import os, shutil, glob

dst_fldr = "~/path/Desktop/newfolder"; 

for jpg_file in glob.glob("~/path/Desktop"+"\\*.jpg"):
    print jpg_file + "will be moved to " + dst_fldr
    shutil.move(jpg_file, dst_fldr);
Drew L. Facchiano
  • 283
  • 3
  • 5
  • 12
  • 1
    Do you have any accompanying output, error or otherwise? – Davy M Jul 06 '17 at 18:01
  • @DavyM No error.... glob returns an empty list in this case and nothing to iterate over in the loop, so the script silently exits. – cs95 Jul 06 '17 at 18:08

1 Answers1

3

~ is not a character that glob understands (it's a character that bash understands and expands). You'll have to provide a full path.

dst_fldr = "/path/to/Desktop/newfolder"; 

In addition, you'd want to modify the wildcard search, to something like this:

glob.glob("/path/to/Desktop/*.jpg"):

If your python script resides in Desktop, you can drop the /path/to/Desktop part of the path in both cases.

With these changes in place, I believe you're good to go.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Wala! This works now :D Thank you very much COLDSPEED. Any chance you know a good way for me to use glob on multiple file types? something that checks ".jpg, .JPG, ,gif," ect. I imagine I could filter with if conditions, my hope is there is something nice I can do with the search already being done – Drew L. Facchiano Jul 06 '17 at 18:55
  • Indeed you can. Specify `/path/to/Desktop/(*.jpg)|(*.gif)`. Add more extensions as needed. – cs95 Jul 06 '17 at 19:00
  • Did'nt seem to work. Ended up throwing another loop around it "for jpg_file in glob.glob("../"+file_type): " – Drew L. Facchiano Jul 06 '17 at 19:19
  • @DrewL.Facchiano Oh, my bad. I guess it isn't possible. Take a look [here](https://stackoverflow.com/questions/4568580/python-glob-multiple-filetypes) though it seems what you've done is good enough. – cs95 Jul 06 '17 at 19:26
  • No worries! Thanks for the help, I'm excited to have this script working :) – Drew L. Facchiano Jul 06 '17 at 20:28
  • @DrewL.Facchiano Glad to have helped. Do consider marking this answer accepted if you feel like it. :) – cs95 Jul 06 '17 at 20:32