I'm making a basic file manager to practice. I've ran into trouble while trying to copy files from a directory, into another already existing directory.
def singulateDataInDir(SRCdir, passBackFiles=bool, passBackDirs=bool):
for root, dirs, files in os.walk(SRCdir, topdown=True):
for name in files:
filesInSRCdir = os.path.join(root, name)
if passBackFiles is True:
return filesInSRCdir
for name in dirs:
dirsInSRCdir = os.path.join(root, name)
if passBackDirs is True:
return dirsInSRCdir
def copyFilesFromSRCtoDEST(SRCdir, DESTdir):
for files in singulateDataInDir(SRCdir, True, False):
shutil.copy2(files, DESTdir)
I attempt to sort through items in the SRCdir and depending on the parameters it returns files, directories, or both. I get an error saying my destination is a directory (I think? perhaps the '/' means that I'm typing the code incorrectly.)
Traceback (most recent call last):
File "main.py", line 45, in <module>
main(True)
File "main.py", line 38, in main
code.copyFilesFromSRCtoDEST(srcOpt, destOpt)
File "/Users/jcrd/Documents/csProjects/pythonProjects/screenshotCollecting/code.py", line 34, in copyFilesFromSRCtoDEST
shutil.copy2(files, DESTdir)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/shutil.py", line 432, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
IsADirectoryError: [Errno 21] Is a directory: '/'
Any help would be amazing, thank you for looking at my question.
The problem is that singulateDataInDir
does not yield filenames and is not a generator. It returns a single path with return filesInSRCdir
and so
for files in singulateDataInDir(SRCdir, True, False):
iterates the characters in the name returned, starting with the leading forward slash "/". Thus the error Is a directory: '/'
. Te fix is to yield
instead of return
. You also need to fiddle with the default parameters to the function. bool
is a type object, it doesn't mean that input has to be a bool.
def singulateDataInDir(SRCdir, passBackFiles=False, passBackDirs=False):
for root, dirs, files in os.walk(SRCdir, topdown=True):
for name in files:
filesInSRCdir = os.path.join(root, name)
if passBackFiles is True:
yield filesInSRCdir
for name in dirs:
dirsInSRCdir = os.path.join(root, name)
if passBackDirs is True:
yield dirsInSRCdir
def copyFilesFromSRCtoDEST(SRCdir, DESTdir):
for files in singulateDataInDir(SRCdir, True, False):
shutil.copy2(files, DESTdir)
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.