2012-10-23 67 views
0

我在这个文件夹结构的许多文件:创建文件夹,并在Python文件复制到他们

test[dir] 
    -test1 - 123.avi 
    -video[dir] 
    -test2 - 123.avi 

我想基于文件名(如TEST1,TEST2)来创建基于文件夹中目标目录并将文件移动到相应的文件夹。

我试过此基础上从另一个线程代码:

#!/usr/bin/env python 

import os, shutil 

src = "/home/koogee/Code/test" 
dest = "/home/koogee/Downloads" 

for dirpath, dirs, files in os.walk(src): 
    for file in files: 
     if not file.endswith('.part'): 
      Dir = file.split("-")[0] 
      newDir = os.path.join(dest, Dir) 
      if (not os.path.exists(newDir)): 
       os.mkdir(newDir) 

      shutil.move(file, newDir) 

我得到这个错误:

Traceback (most recent call last): 
    File "<stdin>", line 8, in <module> 
    File "/usr/lib/python2.7/shutil.py", line 299, in move 
    copy2(src, real_dst) 
    File "/usr/lib/python2.7/shutil.py", line 128, in copy2 
    copyfile(src, dst) 
    File "/usr/lib/python2.7/shutil.py", line 82, in copyfile 
    with open(src, 'rb') as fsrc: 
IOError: [Errno 2] No such file or directory: 'test1' 

是什么奇怪的是,有在/ home创建的文件夹/ koogee /下载命名为'test1'

回答

1

当您尝试执行shutil.move()时,您的file变量仅仅是没有目录上下文的文件名,因此它正在查找第在脚本的当前目录中名称。

为了得到一个绝对路径,使用os.path.join(dirpath, file)作为源:

shutil.move(os.path.join(dirpath, file), newDir) 
+0

噢(前额巴掌)的,我是给人以shutil纯字符串。我浪费了一个小时试图解决这个问题:) – koogee

相关问题