2012-08-14 66 views
1

所以我试图创建一个文件中使用shutil模块文件组织程序

import glob, shutil, os, time, argparse 


src='' 
dest='' 
ext='' 
extention = '' 


def parser(): 
    parser = argparse.ArgumentParser(description='Grab shell flags') 
    parser.add_argument('--src', action="store", dest="src", type=str, default=None) 
    parser.add_argument('--dest', action="store", dest="dest", type=str, default=None) 
    parser.add_argument('--ext', action="store", dest="ext", type=str, default=None) 
    global src 
    global dest 
    global ext 

def if_parser_fails(source_directory, dest_directory, file_extentions): 
    while source_directory is None: 
      global src 
      src = raw_input('What is the directory you wish to monitor?: ') 
    while dest_directory is None: 
      global dest 
      dest = raw_input('Where do you wish to move the files?: ') 
    while file_extentions is None: 
      global extention 
      extention = raw_input('Please input the extension(s), seperated by commas, that you wish to use as criteria for sorting: ') 


def sorter(source_directory, dest_directory, file_extentions): 
    found = glob.glob('%(src)s./*' % {"src": source_directory}) 
    ext_list = file_extentions.split(',') 
    global moving_files 
    moving_files = [] 
    for i in found: 
      (filepath, filename) = os.path.split('%(file)s' % {"file": i}) 
    for h in filename: 
      for j in ext_list: 
        if j in h: 
          moving_files.append(h) 
    else: 
      pass 

def copy_files(to_move, source_directory, dest_directory): 
    for item in to_move: 
      full_path = os.path.join(source_directory, item) 
      full_path_dest = os.path.join(dest_directory, item) 
      shutil.move(full_path, full_path_dest) 
      print("%(file)s has been copied to %(dest)s" % {"file": i, "dest": dest_directory}) 

def log_writer(): 
    log_path = os.path.join(dest, 'log.txt') 
    write_time = time.asctime() 

    with open(log_path, 'ab') as logfile: 
      logfile.write('%(filename)s has been moved \n %(time)s \n \n' % {"filename": filename, "time": write_time}) 
    print file(log_path).read() 

def main(): 
    parser() 
    if_parser_fails(src, dest, ext) 
    sorter(src, dest, extention) 
    copy_files(moving_files, src, dest) 
    log_writer() 
if __name__ == "__main__": 
    main() 

分拣程序,但shutil不断提高的错误:

shutil.Error: `S` and `S` are the same file 

我相信这是与输入和输出目录不知何故被赋值。

任何帮助,将不胜感激。

+3

它是有用的张贴整个回溯,因为错误信息中包含的重要信息,如行号和调用堆栈。 – 2012-08-14 20:07:38

回答

1

很难说没有完整的追踪,但它看起来就像这个segement:

for i in found: 
     (filepath, filename) = os.path.split('%(file)s' % {"file": i}) 
for h in filename: 
     for j in ext_list: 
       if j in h: 
         moving_files.append(h) 

你只取最后一个文件名,并追加该文件名的单个字符来移动文件。

而是尝试:

for i in found: 
     (filepath, filename) = os.path.split('%(file)s' % {"file": i}) 
     for h in filename: 
       for j in ext_list: 
         if j in h: 
           moving_files.append(h)