'Moving multiple files using REGEX to a sub folder
I have some files that include the keyword "Mantech" at the beginning of the file and would like to move them to my "Mantech" folder. I'm looking specifically to move the pdf files that contain the keyword. Code as follows:
import shutil
import os
import re
folder = 'C:/Users/Chris/Documents/ManTech'
keyword = re.compile(r'(^Mantech)(.*)(pdf$)', re.IGNORECASE)
for organization in os.listdir('C:/Users/Chris/Documents'):
`mo = keyword.search(organization)
shutil.move(organization, folder)
I keep getting a "FILENOTFOUNDERROR: No such file or directory" error.
Solution 1:[1]
Regex seems to be overkill for that easy task. You could use globbing instead:
import glob, shutil
sourcedir = 'C:/Users/Chris/Documents'
destdir = 'C:/Users/Chris/Documents/ManTech/'
gl = 'Mantech*.pdf'
for file in glob.glob(sourcedir+gl):
shutil.move(file, destdir)
The downside is that glob does not support case insensitive globbing.
Solution 2:[2]
os.listdir() returns only file names and not the full path. Please use shutil.move(os.path.join('C:/Users/Chris/Documents', organization), folder).
You can move it to a constant of course.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mashuptwice |
| Solution 2 | Bharel |
