I hope below code is the solution for your problem. Please note that I have use os.mkdirs()
to create new directory. but you can try with Path.mkdir()
I have created four text file. out of 4, three text file have strings 2012. and one text file contains string 2020 and three text file contains 2012
Input files:
- ff1.txt (contains string
"2012"
)
- ff2.txt (doesn't contains string
"2012"
)
- ff_blah1.txt (contains string
"2012"
)
- ff_blah1_blah2.txt (contains string
"2012"
)
I have broken down problem statement in steps
- find the files which has name starts with
"ff"
- after finding files, open all the files and search string
"2012"
- create new folder
"2012"
if it doesn't exists
- move all files that we find at step2 into new created folder
"2012"
import os
import shutil
source_path = '/Users/MacJJ271123/Desktop/PY_Script/'
list_of_files = os.listdir(source_path)
def move_file():
for file in list_of_files:
if file.startswith("ff"):
if '2012' in open(file).read():
if not os.path.exists(os.path.join(source_path, "2012")):
os.mkdir(os.path.join(source_path, "2012"))
shutil.move(os.path.join(source_path,file), os.path.join(source_path,"2012",file))
print(file)
move_file()
Output:
MacJ271123-MacBook-Air~ # python3 move_files_stack_oveflow.py
ff_blah1_blah2.txt
ff_blah1.txt
ff1.txt
MacJJ271123-MacBook-Air~ #