Search code examples
pythondirectorywildcardglob

Python wildcard folder with glob


My ant script creates a folder with date and time enf of the folder in D:\test\ folder.

How to copy d:\test\apps_20150709_updates_2015_08_03_13-54\apps\dist\packages\ folder to D:\test\packages. Date and time always changing (2015_08_03_13-54). I tried use glob command in this script can you help me?

import os, shutil, glob

SOURCE = glob.glob("D:\\test\\apps_20150709_updates_*\\apps\\dist\\packages\\")

DEST = "D:\\test\\packages\\"

shutil.copytree(SOURCE, DEST)

print os.listdir(DEST)

***D:\test>python copy_files.py
Traceback (most recent call last):
  File "copy_files.py", line 6, in <module>
    shutil.copytree(SOURCE, DEST)
  File "C:\Python27\lib\shutil.py", line 171, in copytree
    names = os.listdir(src)
TypeError: coercing to Unicode: need string or buffer, list found
D:\test>***

Solution

  • As the other answer points out, you're passing a list to shutil.copytree() which expects each argument to be a string. To fix that, try the following which will copy all matching source folders to the destination folder:

    import os, shutil, glob
    
    SOURCE = glob.glob("D:\\test\\apps_20150709_updates_*\\apps\\dist\\packages\\")
    DEST = "D:\\test\\packages\\"
    
    for folder in SOURCE:
        shutil.copytree(folder, DEST)
    
    print os.listdir(DEST)