【问题标题】:Create folders based on file names and copy files to them in python根据文件名创建文件夹并在python中将文件复制到它们
【发布时间】:2012-10-23 22:21:15
【问题描述】:

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

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' 的文件夹

【问题讨论】:

    标签: python file move


    【解决方案1】:

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

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

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

    【讨论】:

    • 哦,是的(拍在额头上)它是我要给shutil的普通字符串。我浪费了一个小时试图解决这个问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多