一个移动文件的小程序,主要用来对下载的文件分类存放
python 代码
- import os
- import sys
- #shutil is a module for hightlevel file operation
- import shutil
- dir='D:\\Downloads'
- filetype=raw_input('input the ext of the type you want to sort:')
- destdir=raw_input('where you want to put these %s files to:'%filetype)
- destdir.strip()
- if not os.path.exists(destdir):
- choice=raw_input( '%s does not exist,do you want to create it?[y/n]'%destdir)
- if choice.strip()=='y':
- try:
- os.mkdir(destdir)
- except:
- raw_input('failed to creat %s'%destdir)
- sys.exit()
- else:
- raw_input('you choose no,and we cant go on ,good bye!')
- sys.exit()
- filelist=os.listdir(dir)
- for i in filelist:
- #os.path.splitext() split a the name into file and ext and return as a tuple
- if os.path.splitext(i)[1][1:] in filetype:
- command='move %s %s'%(i,destdir)
- try:
- #we convert the string to a raw string
- shutil.move(r'%s'%i,r'%s'%destdir)
- print 'successfully move %s to %s\n'%(i,destdir)
- except:
- print 'error moving %s'%i
- continue
- raw_input('Done')