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.
CodePudding user response:
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.
CodePudding user response:
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.