-1

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))
halfer
  • 19,824
  • 17
  • 99
  • 186
user1452759
  • 8,810
  • 15
  • 42
  • 58

1 Answers1

3

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)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • This code just transfers the files 'jenjar.dat_1' and 'jenmis.dat_1' to '/user/data'. The '/user/data' directory has two subdirectories 'jenmis' and 'jenjar'. I need the 'jenjar.dat_1' to go into 'jenjar' directory and 'jenmis.dat_1' to go into 'jenmis' directory. – user1452759 Oct 15 '12 at 07:34
  • Typo: should be `fname` not `frame` at line 4. Also the directories are `jenjar` and `jenmis` not `jenjar.dat`, so you shouldn't use `prefix` to create the dir. – Bakuriu Oct 15 '12 at 08:04
  • There are some changes that I made to this code and I have edited my question to include the answer as well. Thank you for helping me out. – user1452759 Oct 16 '12 at 08:50