简体   繁体   中英

Copy files with same extensions in the same directory to another directory - Python

I have some files in the same directory which have the same extension(.html). Those files need to all be copied to another directory. I've looked up documentations on both shutil and os but couldn't find any proper answer...

I have some pseudo codes as below:

import os, shutil

copy file1, file2, file3 in C:\abc
to C:\def

If anyone knows how to solve this, pls let me know. Appreciated!!

Some time ago I created this script for sorting files in a folder. try it.

import glob
import os

#get list of file 
orig = glob.glob("G:\\RECOVER\\*")

dest = "G:\\RECOVER_SORTED\\"

count = 0

#recursive function through all the nested folders
def smista(orig,dest):
    for f in orig:
            #split filename at the last point and take the extension
            if f.rfind('.') == -1:
                #in this case the file is a folder
                smista(glob.glob(f+"\\*"),dest)
            else:
                #get extension
                ext = f[f.rfind('.')+1:]

                #if the folder does not exist create it
                if not os.path.isdir(dest+ext):
                    os.makedirs(dest+ext)
                global count
                os.rename(f,dest+ext+"\\"+str(count)+"."+ext)
                count = count+1
#if the destination path does not exist create it            
if not os.path.isdir(dest):
            os.makedirs(dest)

smista(orig,dest)
input("press close to exit")

[assuming python3, but should be similiar in 2.7]

you can use listdir from os and copy from shutil:

import os, shutil, os.path

for f in listdir("/path/to/source/dir"):
    if os.path.splitext(f)[1] == "html":
        shutil.copy(f, "/path/to/target/dir")

warning: this is scrapped together without testing. corrections welcome

edit (cause i can't comment): @ryan9025 splitext is from os.path , my bad.

I finally got an correct answer by myself with a combinations of all the replies.

So if I have a python script in (a) directory, all the source files in (b) directory, and the destination is in (c) directory.

Below is the correct code that should work, and it looks very neat as well.

import os
import shutil
import glob

src = r"C:/abc"
dest = r"C:/def"

os.chdir(src)
for files in glob.glob("*.html"):
        shutil.copy(files, dest)

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