简体   繁体   中英

OSError: [Errno 21] Is a directory

I am trying to make a video mover but when I try to run it, it comes up with this error:

Traceback (most recent call last):
  File "/home/zac/programs/VideoMover/core.py", line 25, in <module>
    os.rename(source, root.replace(topfolder, "/home/zac/Videos/") +"/"+filename)
OSError: [Errno 21] Is a directory

Here is my code:

import os
import errno
import fnmatch
if __name__ == '__main__':
    patterns= ["*.mov", "*.mp4", "*.avi"]
    topfolder= "xyxyxyxy"
    while not os.path.exists(topfolder):

        topfolder=raw_input("Please input folder for searching: ")
    if topfolder[-1] != "/":
        topfolder= topfolder + "/"
    for root, dirs, files in os.walk(topfolder): 
        for pattern in patterns:
            for filename in fnmatch.filter(files, pattern):


                source= root+"/"+filename
                print source
                print root.replace(topfolder, "/home/zac/Videos/") +"/"+filename
                try:
                    os.makedirs(root.replace(topfolder, "/home/zac/Videos/"))
                except OSError, e:
                    if e.errno != errno.EEXIST: 
                        raise
                    os.rename(source, root.replace(topfolder, "/home/zac/Videos/") +"/"+filename)
    print "done!"

That's it. Any help is welcome!

os.rename raise if source is fiel, destination is directory.

/tmp$ touch a
/tmp$ mkdir b
/tmp$ python
Python 2.7.4 (default, Apr 19 2013, 18:32:33)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.rename('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 21] Is a directory

Try following code:

import os
import shutil

def find_movie_files(topdir):
    extensions = (".mov", ".mp4", ".avi",)
    for root, dirs, files in os.walk(topdir):
        for filename in files:
            if filename.endswith(extensions):
                yield os.path.join(root, filename)

def move_file(src, dst):
    d = os.path.dirname(dst)
    if not os.path.exists(d):
        print 'Make directory: ', d
        os.makedirs(d)
    print 'Move', src, 'to', dst
    shutil.move(src, dst)

if __name__ == '__main__':
    src_dir =  "xyxyxyxy"
    dst_dir = '/home/zac/Videos'
    while not os.path.exists(src_dir):
        src_dir = raw_input("Please input folder for searching: ")

    for filepath in find_movie_files(src_dir):
        src = filepath
        dst = os.path.join(dst_dir, os.path.relpath(filepath, src_dir))
        move_file(src, dst)
    print "done!"

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