Search code examples
pythontransfer

How to move files based on their names to specific directories in python?


I have a directory called /user/local/ inside which i have several files of the form, jenjar.dat_1 and jenmis.dat_1. There is another directory /user/data inside which there are two subdirectories of the form, jenjar and jenmis. I need a Python code that would move the jenjar.dat_1 into the jenjar directory of /user/data and similarly, jenmis.dat_1 into jenmis directory of '/user/data.

I guess the os module would work for thus but I'm confused. Most of the questions here do not show a Pythonic way to do this.

EDIT: I have found the solution to this

destination = '/user/local'
target = '/user/data'
destination_list = os.listdir(destination)
data_dir_list = os.listdir(target)
for fileName in destination_list:
   if not os.path.isdir(os.path.join(destination, fileName)):
       for prefix in data_dir_list:
           if fileName.startswith(prefix):
               shutil.copy(os.path.join(destination, fileName), os.path.join(target, prefix, fileName))

Solution

  • This should do the trick

    srcDir = '/user/local'
    targetDir = '/user/data'
    for fname in os.listdir(srcDir):
        if not os.path.isdir(os.path.join(srcDir, fname)):
            for prefix in ['jenjar.dat', 'jenmis.dat']:
                if fname.startswith(prefix):
                    if not os.path.isdir(os.path.join(targetDir, prefix)):
                        os.mkdir(os.path.join(targetDir, prefix))
                    shutil.move(os.path.join(srcDir, fnmae), targetDir)