Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to copy a file in Python script, but it doesn't work

I'm trying to copy a file (image.jpg) from the folder 'src' to the folder 'dst', but I've got an error:

Traceback (most recent call last): File "exec.py", line 7, in shutil.copyfile(file, destination) File "C:\Users\mike\AppData\Local\Programs\Python\Python35-32\lib\s hutil.py", line 114, in copyfile with open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: 'image.jpg'

This is my code:

import shutil, os

source = os.listdir('C:/Users/mike/Pictures/src/')
destination = 'C:/Users/mike/Pictures/dst/'

for file in source:
    shutil.copy(file, destination)

Python 3.5 / Windows 7

like image 672
Renzo Rodrigues Avatar asked Nov 16 '25 12:11

Renzo Rodrigues


1 Answers

os.listdir returns the names, but they don't have the directory prefix on them, you need to add this when copying.

for file in source:
    shutil.copy(os.path.join('C:/Users/mike/Pictures/src/', file), destination)
like image 153
Barmar Avatar answered Nov 19 '25 03:11

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!