1

我在这个文件夹结构中有很多文件:

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/Downloads 中创建了一个名为“test1”的文件夹

4

1 回答 1

2

当您尝试这样做时shutil.move(),您的file变量只是没有目录上下文的文件名,因此它正在脚本的当前目录中寻找该名称的文件。

要获取绝对路径,os.path.join(dirpath, file)请用作源:

shutil.move(os.path.join(dirpath, file), newDir)
于 2012-10-23T22:24:14.753 回答