简体   繁体   中英

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

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)

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