简体   繁体   中英

Script to copy multiple files to multiple directories

I have a directory containing many files:

abc.txt
def.txt
ghi.txt
   etc.

I have written a script which creates a new directory based on the name of each file (Directories abc, def, ghi etc.).

Now I want to copy file abc.txt into directory abc, file def.txt into directory def and so on.

I'm trying to do this using shutil but my script doesn't work.

import os, glob, shutil

myfiles = glob.glob("/users/source_directory/*.*")
for f in myfiles:
    file_name, file_extension = os.path.splitext(f)
    destination = (os.path.join('/users/destination_directory/',file_name))
    shutil.copy(f, (os.path.join(destination,file_name)))

This produces a copy of the source file minus its file extension in the source directory. Any suggestions for how to get it to work as intended?

First, your file_name variable does not contain only the file name but the whole absolute path of the file. This means that the os.path.join command for your destination variable overrides the /users/destination_directory path by /users/source_directory.

Second, you have to create the new directories.

Third, I added also the file extension for the copy process.

The following code is doing your job.

import os, glob, shutil

myfiles = glob.glob("/users/source_directory/*.*")
for f in myfiles:
    file_path, file_extension = os.path.splitext(f)
    file_name = os.path.basename(file_path)
    destination = os.path.join('/users/destination_directory/',file_name)
    os.mkdir(destination)
    shutil.copy(f, (os.path.join(destination,file_name+file_extension)))

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