简体   繁体   中英

Python copy files to folder

I'm currently trying to copy files from one folder to another (without knowing the names of the files)

However, it's not working and I can't seem to understand why. Below is the code and the error code:

#!/usr/bin/python
import sys, os, time, shutil

path = '/home/images/'
files = os.listdir(path)
files.sort()
for f in files:
        src = path+f
        dst = '/USB/images/' +f
        shutil.move(src, dst)

And the error:

Traceback (most recent call last):
  File "copy.py", line 10, in <module>
    shutil.move(dst, src)
  File "/usr/lib/python2.7/shutil.py", line 301, in move
    copy2(src, real_dst)
  File "/usr/lib/python2.7/shutil.py", line 130, in copy2
    copyfile(src, dst)
  File "/usr/lib/python2.7/shutil.py", line 82, in copyfile
    with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: '/USB/images/26-07-2015-18:06:22-01.jpg'

Can anybody help me in the right direction? Thanks!

The code and error message don't appear to tally up to one another.

The code suggests you're calling

shutil.move(src, dst)

but the error suggests you're calling

shutil.move(dst, src)

If you're doing the latter then clearly the error message makes sense if the /USB/images/26-07-2015-18:06:22-01.jpg does not already exist.

You may also have trouble using : characters in the filenames. The FAT (or derivative) filesystem is common on (typically smaller) USB devices. That filesystem type does not permit any of the following characters in filenames: "/\\*?<>|: .

它应该是:

shutil.move(dst, src)

Looks like your destination dir is not writable, or non-existent? What do you see when you do ls -l /USB/images ?

BTW, I thought you wanted to copy? shutil.move will move the file, not copy.

EDIT: destination VFAT requires special file conversion

How about this:

#!/usr/bin/python
import sys, os, time, shutil

path = '/home/images/'
files = os.listdir(path)
files.sort()
for f in files:
    f_dst = f.replace(':','_')
    src os.path.join(path, f)
    dst = os.path.join('/USB/images/', f_dst)
    shutil.move(src, dst)

Use the OS-agnostic function os.path.join() to effectively concatenate file names to folder paths.

#!/usr/bin/python
import sys, os, time, shutil

path = '/home/images/'

files = os.listdir(path)
files.sort()
for f in files:
  src = os.path.join(path, f)
  dst = os.path.join('/USB/images/', f)
  shutil.move(src, dst)

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