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

扶醉桌前 提交于 2019-12-12 07:04:29

问题


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))

回答1:


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)


来源:https://stackoverflow.com/questions/12890812/how-to-move-files-based-on-their-names-to-specific-directories-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!