Search code examples
pythonmovecontains

Python Moving files script, 'startswith' and 'endswith', but, how to find contains or partial matches based on user input


I have the following script

import os
import shutil


################# MOVE FILES SCRIPT ############################
# Moving files from one folder to another based on file names starting or ending with input

# Step 1: Source Directory / Folder
movefrom_path = input('Enter the move from path of the directory:') 

# Step 2: Destination Directory / Folder
moveto_path = input("Enter the move to path of the directory:")  

# Step 3: Create folder if it doesn't exist
if not os.path.exists(moveto_path):  
    os.makedirs(moveto_path)
    
# Step 4: What is the name or number we are trying to match (I was searchinng contract number)
filename_match = input("Enter characters of type of file you want to move:") 

# Not working: Does the file start or end with name number we are trying to match 
# starts_ends = input("Enter 'startswith' or 'endswith' with file name match you just entered:")

# Step 5: List all the files in directory with os
entries = os.listdir(movefrom_path)

# Step 6: Run iterate 'for' 'in' loop
for entry in entries:
    # could also you 'startwith' if file name starts instead of ends with input from filename_match
     if entry.startswith(filename_match):
        shutil.move(movefrom_path + entry, moveto_path)
 
print('Done.')

However, in step 6, I would like to search for file names based on 'contains', not only 'startswith' or 'endswith'. How can I get the for in loop to iterate based on match within filename, e.g. 356333 (customer number, contract number, etc). I cannot replace 'startsWith' or 'endsWith' with 'contains'


Solution

  • if filename_match in entry:
    

    instead of

    if entry.startswith(filename_match):
    

    perfectly solves my question.