简体   繁体   中英

Create folders based on file names and copy files to them in python

I have many files in this folder structure:

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

I want to create folders based based on file names (eg test1, test2) in the target dir and move files to respective folders.

I tried this based on code from another thread:

#!/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)

I get this error:

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'

What is weird is that there is a folder created in /home/koogee/Downloads named 'test1'

When you try to do shutil.move() , your file variable is just the file name with no context of the directory, so it is looking for a file of that name in the script's current directory.

To get an absolute path, use os.path.join(dirpath, file) as the source:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM