1

Continusly to How can i move files from one directory to another? i try to move all jpg files from folder r"C:\Project\layers" to folder r"C:\Project\layers\new" with this code, but i get en error:

import shutil, os
source = r"C:\Project\layers"
destination = r"C:\Project\layers\new"
if not os.path.exists(destination):
    os.makedirs(destination)               
for f in os.listdir(source):
    if f.endswith(".jpg"):
        shutil.move(source + f, destination)

the error:

Traceback (most recent call last):
  File "C:\Users\yaron.KAYAMOT\Desktop\python.py", line 8, in <module>
    shutil.move(source + f, destination) # add source dir to filename
  File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 302, in move
    copy2(src, real_dst)
  File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 130, in copy2
    copyfile(src, dst)
  File "C:\Python27\ArcGISx6410.3\lib\shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'C:\\Project\\layerslogo1.jpg'
>>> 
Community
  • 1
  • 1
newGIS
  • 598
  • 3
  • 10
  • 26
  • It’s not adding a slash between the directory name (layers) and the filename (logo1.jpg), so it's looking for a file called `layerslogo1.jpg` in the `Project` directory. You need to add the slash yourself in `source + f`, or better, use `os.path.join(source, f)`. – alexwlchan May 04 '15 at 11:16
  • You should learn to read the error messages: “No such file or directory: 'C:\\Project\\layerslogo1.jpg'”. Does `C:\\Project\\layerslogo1.jpg` exist? No it doesn’t. Then your next question is why your program tries to use that path instead of the correct one `C:\\Project\\layers\logo1.jpg`. – poke May 04 '15 at 11:18
  • poke,what do you mean? – newGIS May 04 '15 at 11:32

1 Answers1

3

You need to join the path to the file:

os.path.join(source,f)

layers is a directory so ...layers+filename does not exist but ...layers\filenamedoes. You are concatenating the two strings, you could have use source = r"C:\Project\layers\" with a backslash at the end but probably best to use join.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321