Reputation: 435
I wrote the following code to recognize and organize gif and image files. cdir
refers to the directory the program is supposed to organize. When it is executed, it should create folders 'Gifs' and 'Images' in the same directory.
import shutil, os
gifext = ['.gif', 'gifv']
picext = ['.png', '.jpg']
for file in files:
if file.endswith(tuple(gifext)):
if not os.path.exists(cdir+'\Gifs'):
os.makedirs(cdir + '\Gifs')
shutil.move(cdir + file, cdir + '\Gifs')
elif file.endswith(tuple(picext)):
if not os.path.exists(cdir+'\Images'):
os.makedirs(cdir + '\Images')
shutil.move(cdir + file, cdir + '\Images')
The directory contains the files: FIRST.gif, SECOND.gif and THIRD.jpg
But I get the following error:
File "test.py", line 16
shutil.move(cdir + file, cdir + '\Gifs')
File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 552, in move
copy_function(src, real_dst)
File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 251, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\stavr\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 114, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif'
Upvotes: 2
Views: 6797
Reputation: 1
Following the error report there is a "\" missing in the path between your directory "test" und the file "FIRST.gif":
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\stavr\\Desktop\\testFIRST.gif'
You can resolve this by adding "\" when you put in the path like this:
Enter path to the directory: C:\Users\stavr\Desktop\test\
OR
replace:
shutil.move(cdir + file, cdir + '\Gifs')
by:
shutil.move(os.getcwd() + '/' + file, cdir + '\Gifs')
By the way: I think here's a "." missing before "gifv"
gifext = ['.gif', 'gifv']
Upvotes: 0
Reputation: 23064
Your file path is incorrect. There's a path separator missing.
shutil.move(os.path.join(cdir, file), os.path.join(cdir, 'Gifs'))
Upvotes: 1
Reputation: 44828
files
contains only the names of the files in a directory. cdir
doesn't have a backslash at the end, so, when you concatenate cdir
with an element of files
you get a potentially invalid path:
"C:\stuff\my\path" + "file_name.png"
# equals
"C:\stuff\my\pathfile_name.png"
The latter is obviously not what you wanted, so you should add that backslash to cdir
somehow, maybe like this:
if not cdir.endswith("\\"):
cdir += "\\"
Upvotes: 3