Help! I was writing a script to organize my desktop by moving files with certain extensions. It seemed to work fine but when I let it loose on my Desktop something strange happened.
So I copy all the files into folders created on the fly like ‘PDFs’ and ‘IMAGES’ but for some reason when I ran the script it create no folders but files and proceeded to store the files within another file.
I need to get these guys back but I have no idea what to do. I am using Windows 7 by the way. Below is my code. Any help would be appreciated.
import shutil
import os
pwd = os.getcwd()
working_path = 'C:\\Users\\grayson\\Desktop'
wp = working_path
folders = {'pdf':'PDFS','img':'IMAGES'}
def main():
create_folders();
for d in os.walk(wp):
files = d[2]
break
print files
for filename in files:
order_file( filename )
def create_folders():
for fol in folders.keys():
fol_name = folders[fol]
if not os.path.isdir(fol_name):
os.mkdir(fol_name)
def order_file(fname):
split_name = fname.split('.')
exten = split_name[len(split_name)-1]
if exten == 'pdf':
shutil.move(wp + '\\' + fname, wp + '\\' + folders['pdf'])
elif exten == 'jpg' or exten == 'png' or exten == 'gif':
shutil.move(wp + '\\' + fname, wp + '\\' + folders['img'])
else:
print 'Sumin else'
main()
This is a very awkward script for essentially moving files into sorted directories. But here is my guess as to what went wrong. If you did not run this with
Desktopas your current working directory (meaning you were not in this directory when you ran the script), then the folders were made in some other location. Then when your files started to move, the directories didn’t exist, so it just moved them over each other as new files.Unfortunately, you cannot reverse this damage. Your only hope is that you have backups.
Let me explain some parts of your script in more detail…
If
pwdis not the same asworking_path, everything will go wrong in your script. Also, you should always use forward slashes, even on windows. Its valid and its easier for path building:working_path = 'C:/Users/grayson/Desktop'Your folder creation section:
You don’t ensure that the directories are actually created under your
working_pathvariable. You could have written this as:That right there would have probably saved you. It would have made the directories specifically under
Desktopinstead of wherever you ran the script from.Lot of typing to get the extension. You could have made this easier by:
And lastly, the part where you move the files:
You built the paths by adding slashes and only build the destination to the directory name. If that directory didnt exist, it will assume its a file. You should have built it to the specific file name:
This way it will be sure to have failed if the directory didn’t exist.