Search code examples
pythoncopy

Copying specific files based on multiple strings with file name in Python


I want to copy specific files based on string what I assign to another directory. My question similar to text But in my loc folder have many file like: File name is different.

20220101(100000-19999).xlsx
20220101(200000-29999).xlsx
20220101(300000-39999).xlsx
20220101(400000-49999).xlsx
20220101(500000-69999).xlsx
20220101(600000-69999).xlsx
20220101(700000-79999).xlsx
20220101(800000-89999).xlsx
20220101(900000-99999).xlsx
20220101(1000000-109999).xlsx
20220101(1100000-119999).xlsx

So far I'm not able to copy files successfully with the below code also:

import shutil
import os
import glob

loc= 'C:/path/to/files/folder'
des = 'G:/path/to/files/new_folder'

pattern= ["100000", "500000"]
patterns= [f"20220101({i}*" for i in pattern]


files = Path(loc).rglob(patterns)

for file in files:
    print(file)
    shutil.copy(file, des )

I want get like below in my des folder when I assign pattern is "100000" and "500000".

20220101(100000-19999).xlsx
20220101(500000-69999).xlsx

Can anyone help? Thanks in advance!


AttributeError                            Traceback (most recent call last)
Cell In[16], line 10
      5 patterns= [f"20220101({i}*" for i in pattern]
      8 files = Path(loc).rglob(patterns)
---> 10 for file in files:
     11     print(file)
     12     shutil.copy(file, des)

File ~\anaconda3\lib\pathlib.py:1043, in Path.rglob(self, pattern)
   1038 """Recursively yield all existing files (of any kind, including
   1039 directories) matching the given relative pattern, anywhere in
   1040 this subtree.
   1041 """
   1042 sys.audit("pathlib.Path.rglob", self, pattern)
-> 1043 drv, root, pattern_parts = self._flavour.parse_parts((pattern,))
   1044 if drv or root:
   1045     raise NotImplementedError("Non-relative patterns are unsupported")

File ~\anaconda3\lib\pathlib.py:66, in _Flavour.parse_parts(self, parts)
     64     continue
     65 if altsep:
---> 66     part = part.replace(altsep, sep)
     67 drv, root, rel = self.splitroot(part)
     68 if sep in rel:

AttributeError: 'list' object has no attribute 'replace'


Solution

  • I suppose it can work in this way.

    import shutil
    from pathlib import Path
    
    loc = 'C:/path/to/files/folder'
    des = 'G:/path/to/files/new_folder'
    
    pattern = ["100000", "500000"]
    patterns = [f"20220101({i}*" for i in pattern]
    
    files = []
    for pat in patterns:
        files = files + sorted(Path(loc).rglob(pat))
    
    for file in files:
        print(file)
        shutil.copy(file, des)
    

    Cause rglob takes str as arg, but which you give was a list.