Home > Software design >  Python Sort files with particular filename into specific folder
Python Sort files with particular filename into specific folder

Time:08-06

Sample Environment

    import os
    import shutil
    for filenames in os.getcwd():
       if filename.contains ('smallpig'):
            os.mkdir('Pig')
            chdir('Pig')
            os.mkdir(smallpig)
#move all the filenames which contain the name pig in it
            shutil.copy(filename-with-smallpig, Pig/smallpig)
       if if filename.contains ('dog'):
            os.mkdir('Dog')
            #move all the filenames which contain the name Dog in it
            shutil.copy(filename-with-dog, Dog)

How to do that in Python ? I have already tried a little but there are many errors

CodePudding user response:

os.getcwd() returns current working directory, you can't get file names out of there. You have to use os.listdir() and may use a condition to choose files and avoid directories (as shown below).

Also using os.mkdir() in loop will throw errors because you can't create an already existing directory. So you should check if it already exists.

Try something like this

import os
import shutil
cwd = os.getcwd()
files = (file for file in os.listdir(cwd) 
         if os.path.isfile(os.path.join(cwd, file)))
for filename in files:
   print(filename)
   if 'pig' in filename:
        if not os.path.exists('Pig'):
            os.mkdir('Pig')
        #move all the filenames which contain the name pig in it
        shutil.copy(filename, './Pig/' filename)
   elif 'dog' in filename:
        if not os.path.exists('Dog'):
            os.mkdir('Dog')
        #move all the filenames which contain the name Dog in it
        shutil.copy(filename, './Dog/' filename)

CodePudding user response:

If you want to copy files you could simply read the binary data and write in a new file:

import os

def copy_file(src_file,dst_folder,cat):
    cat_folder = os.path.join(dst_folder,cat)

    #check specific category folder is exitst
    if not os.path.isdir(cat_folder):
       os.mkdir(cat_folder)

    # Copying file by reading binary data and write in dst file
    with open(src_file.path,'rb') as src:
        data = src.read()
        with open(os.path.join(cat_folder,src_file.name),'wb') as dst:
            dst.write(data)

and your main function should be like:

def main():
    src_folder = os.path.join('YOUR_SOURCE_PATH')
    dst_folder = os.path.join('YOUR_DESTIONATION_PATH')

    if not os.path.isdir(dst_folder):
        os.mkdir(dst_folder)

    # Move the pointer to the destionation folder
    os.chdir(dst_folder)

    # Scan folder items and check is file
    for item in os.scandir(src_folder):
        if item.is_file():
            if 'pig' in item.name:
                copy_file(item,dst_folder,'pig')
            if 'dog' in item.name:
                copy_file(item,dst_folder,'dog')
if __name__ == '__main__':
    main()
  • Related